题目链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/

一次遍历:O(n)

为什么说这道题经典呢,其实是答案更加的经典:

c# Leetcode 121. 买卖股票的最佳时机 (数组*经典O(n))

public class Solution {
    public int MaxProfit(int[] prices) {
        int minprice = int.MaxValue;
			int maxprofit = 0;
			for (int i = 0; i < prices.Length; i++)
			{
				if (prices[i]<minprice)
				{
					minprice = prices[i];
				}
				else if (prices[i]-minprice>maxprofit)
				{
					maxprofit = prices[i] - minprice;
				}
			}
			return maxprofit;
    }
}

使我们感兴趣的点是上图中的峰和谷。我们需要找到最小的谷之后的最大的峰。 我们可以维持两个变量——minprice 和 maxprofit,它们分别对应迄今为止所得到的最小的谷值和最大的利润(卖出价格与最低价格之间的最大差值)。

相关文章:

  • 2022-12-23
  • 2021-11-21
  • 2021-09-16
  • 2021-09-28
  • 2021-09-09
  • 2021-11-02
猜你喜欢
  • 2021-12-06
  • 2021-09-26
  • 2022-12-23
  • 2021-04-03
  • 2021-06-21
相关资源
相似解决方案