例题:

https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/description/
分析:
某一天买入股票,未来任意一天卖出,只能卖了再买,但可以买卖多次,并允许同一天卖出后再买入,求最大利润。
因为要保证利润最大,只能逢涨就买入,遇跌不买。
有利润就买卖,只看眼前。

先定义两个指针i ,j ,i表示当前股票的价格, j表示下一天股票价格,只要有利润就记录。
代码实现:
java
package leetcodeup;
public class ShareslLeetcode122 {
public static int maxProfit(int[] prices) {
int i = 0;
int j = 1;
int sum = 0;
while(j < prices.length){
if(prices[j] - prices[i] > 0){ //有利润
sum += prices[j] - prices[i];
}
i++;
j++;
}
return sum;
}
public static void main(String[] args) {
System.out.println(maxProfit(new int[]{9, 3, 12, 1, 2, 3})); // 11
System.out.println(maxProfit(new int[]{7, 1, 5, 3, 6, 4})); // 7
}
}