122. Best Time to Buy and Sell Stock II
Last updated
Last updated
/**
* Time complexity : O(N)
* Space complexity : O(1)
*/
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length < 2) return 0;
int maxProfit = 0;
for(int i = 1; i < prices.length; i++) {
if(prices[i-1] < prices[i]) {
maxProfit += (prices[i]-prices[i-1]);
}
}
return maxProfit;
}
}/**
* Time complexity : O(N)
* Space complexity : O(1)
*/
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length < 2) return 0;
int n = prices.length;
int i = 0, lowPrice = 0, highPrice = 0, maxProfit = 0;
while(i < n-1) {
while(i < n-1 && prices[i] >= prices[i+1]) {
i++;
}
lowPrice = prices[i];
while(i < n-1 && prices[i] <= prices[i+1]) {
i++;
}
highPrice = prices[i];
maxProfit += (highPrice-lowPrice);
}
return maxProfit;
}
}