https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
解法1:双指针
buy指针记录购买时的价格,i指针遍历数组
若当前价格小于buy价格,则更新buy价格
若当前价格-buy价格大于当前最大利润,则更新当前最大利润
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public: int maxProfit(vector<int>& prices) { int n=prices.size(); int buy=0; int res=0; for(int i=0;i<n;i++) { if(prices[i]<prices[buy]) buy=i; if(prices[i]-prices[buy]>res) res=prices[i]-prices[buy]; } return res; } };
|