方法:记录便利过程中的best profit
class Solution { public: int maxProfit(vector<int>& prices) { if(prices.size() < 2) return 0; int profit = 0, minValue = prices[0]; for(int i=0; i<prices.size(); ++i) { profit = max(profit, prices[i] - minValue); if(prices[i] < minValue) minValue = prices[i]; } return profit; } };
Best Time to Buy and Sell Stock II
class Solution { public: int maxProfit(vector<int>& prices) { int sum = 0; for(int i=1; i<prices.size(); ++i) { if(prices[i] - prices[i-1] > 0) sum += prices[i] - prices[i-1]; } return sum; } };
时间: 2024-10-14 00:54:26