version at: 2022-04-21
/**
1. 找到每一段连续上升子数组的差值
2. 尝试从某个数开始向右扩展, 直到下一个数 a[i+1] < a[i] 时停止, 并记录
3. 结果为所有差值的和
*/
class Solution {
public int maxProfit(int[] prices) {
if (prices == null) return 0;
int sum = 0;
for (int i = 0, j = 0; j < prices.length; j++) {
if (j == prices.length-1 || prices[j] > prices[j+1]) {
sum += prices[j] - prices[i];
i = j+1;
}
}
return sum;
}
}
/*
1. 只能串行的买卖 -> 找出所有连续上升区间并累加所有 区间尾减区间头的差
*/
class Solution {
public int maxProfit(int[] prices) {
int i = 0,j = 0, n = prices.length;
int res = 0;
while (j < n && i < n){
if (j == n-1|| prices[j] > prices[j+1] ){
res += prices[j] - prices[i];
i = j+1;
}
j++;
}
return res;
}
}