![](https://img-blog.csdnimg.cn/direct/f5b982084f9742c4bf171526bf58d927.png)
思路
遍历数组,把所有利润加一起。
解题方法
定义一个变量最大利润初始化为0,从1索引开始遍历数组,如果当前元素比前一个元素大,求出利润累加到最大利润上。
class Solution {
public int maxProfit(int[] prices) {
int maxProfit = 0;
for(int i = 1; i < prices.length; i++){
if(prices[i] > prices[i - 1]){
maxProfit += prices[i] - prices[i - 1];
}
}
return maxProfit;
}
}
![](https://img-blog.csdnimg.cn/direct/4730d2c97f40420493791ae30be32110.png)