- 算法
贪心、动态规划 - 核心思想
只要挣钱我就买,两两做差,如果大于0,我就买,小于0我就留着。实际上总利润就是所有大于0的差值的和。 - 代码
class Solution {
public int maxProfit(int[] prices) {
int[] temp = new int[prices.length - 1];
int total = 0;
for(int i = 1,j = 0;i < prices.length;i++,j++){
temp[j] = prices[i] -prices[i-1];
}
for(int i = 0;i < temp.length;i++){
if(temp[i] >= 0) total += temp[i];
}
return total;
}
}

本文探讨了一种简单的贪心策略解决股票买卖问题,通过两两价格差判断买入时机,并计算所有正收益之和作为最终利润。代码实例展示了如何使用Java实现这一算法。
440

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



