典型的贪心问题。
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() <=1 ) return 0;
int max = 0;
for(size_t i = 0; i <= prices.size()-2; i++)
max = prices[i+1] - prices[i] > 0? max + prices[i+1] - prices[i] : max;
return max;
}
};
本文介绍了一个典型的贪心算法问题——股票买卖的最大利润计算。通过遍历价格数组,算法逐次比较相邻两天的价格差,如果后一天的价格高于前一天,则将差价累加到总利润中,最终返回累计的最大利润。
409

被折叠的 条评论
为什么被折叠?



