class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int total = 0;
for (int i = 0; i < prices.length - 1; i++) {
if (prices[i] < prices[i + 1]) {
total += prices[i + 1] - prices[i];
}
}
return total;
}
}
- Time O(n) space O(1)
- The idea is very simple. Add up all difference between prices[i + 1] and prices[i] if prices[i + 1] > prices[i].