121. Best Time to Buy and Sell Stock

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了121. Best Time to Buy and Sell Stock相关的知识,希望对你有一定的参考价值。

  不定期更新leetcode解题java答案。

  采用pick one的方式选择。

  题意为只允许一次买卖,给定数组为当天物品价格,问最大获益是多少。

  显然获取最大利益的方法是遍历数组,在遍历的过程中,每读取一天的价格,将之与前面遍历获取的最小值进行差运算,此为在该天卖出单次可获得最大收益。将其储存起来,并在随后的操作进行与后来的值进行比较,择取更大值,最后结果为单次交易可能最大的结果。

  代码如下:

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         if(prices.length == 0)
 4             return 0;
 5         int minPrice = prices[0], max = 0;
 6         for(int i = 1; i < prices.length; i++){
 7             if(prices[i] - minPrice > max)
 8                 max = prices[i] - minPrice;
 9             if(prices[i] < minPrice)
10                 minPrice = prices[i];
11         }
12         return max;
13     }
14 }

  最近在了解python,偶尔也会将python版本发出。

 1 class Solution(object):
 2     def maxProfit(self, prices):
 3         """
 4         :type prices: List[int]
 5         :rtype: int
 6         """
 7         if len(prices) == 0:
 8             return 0
 9         max = 0
10         minPrice = prices[0]
11         
12         for price in prices:
13             if max < price - minPrice:
14                 max = price - minPrice
15             if price < minPrice:
16                 minPrice = price
17                 
18         return max

 

以上是关于121. Best Time to Buy and Sell Stock的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stockeasy

121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock