122. Best Time to Buy and Sell Stock II
Intuition
go for every possible solution
Approach
we can solve it using greedy algorithm where we calculate the profite without looking for fourther
Complexity
Time complexity: O(n)
Space complexity: O(1)
Code
class Solution {
public int maxProfit(int[] prices) {
int max = 0;
int buyPrice = prices[0];
for(int i = 0; i < prices.length; i++){
if(prices[i] > buyPrice){
max += prices[i] - buyPrice;
}
buyPrice = prices[i];
}
return max;
}
}
Comments
Post a Comment