当前位置: 代码迷 >> 综合 >> leetcode 121. Best Time to Buy and Sell Stock 股票一次买入一次卖出的最大利润
  详细解决方案

leetcode 121. Best Time to Buy and Sell Stock 股票一次买入一次卖出的最大利润

热度:49   发布时间:2023-12-15 14:54:27.0

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

滑动更新最低价、最大收益值。

class Solution {
public:int maxProfit(vector<int>& prices) {int n = prices.size();if(n<2) return 0;int p = 0;int low = prices[0];int i;//滑动更新最小值、收益最大值for(i=1;i<n;i++){if(prices[i]>low){if(p<prices[i]-low)p = prices[i]-low;}elselow = prices[i];}return p;}
};

 

  相关解决方案