Best Time Buy/Sell Stock II — Unlimited Transactions
Advertisement
Problem
Unlimited transactions (buy and sell as many times as you want, but only one share at a time). Maximize profit.
Approach — Greedy (every upward slope)
If prices[i] > prices[i-1], add the difference.
Time: O(n) | Space: O(1)
Solutions
Python
class Solution:
def maxProfit(self, prices: list[int]) -> int:
return sum(max(0, prices[i]-prices[i-1]) for i in range(1,len(prices)))
C++
class Solution {
public:
int maxProfit(vector<int>& p){
int res=0;
for(int i=1;i<p.size();i++) res+=max(0,p[i]-p[i-1]);
return res;
}
};
Complexity
- Time: O(n) | Space: O(1)
Advertisement