122. Best Time to Buy and Sell Stock II
Asked at 26Apple67Amazon58Bloomberg56Meta49Google48Microsoft46Infosys58Meesho57Careem100Toast91Nike89Sigmoid87ServiceNow73Groww68Geico66Optiver57eBay53Agoda48Goldman Sachs48Accenture44Zoho42Nvidia39Visa39tcs36TikTok35Atlassian34
Problem
prices[i] is a stock's price on day i. Buy and sell as often as you like, holding at most one share at a time (you may sell and buy again on the same day). Return the maximum profit.
Example: [7,1,5,3,6,4] → 7 (buy 1 sell 5, buy 3 sell 6); [1,2,3,4,5] → 4
Unlimited transactions → collect every positive day-to-day increase.
Complexity: O(n).
class Solution:
def maxProfit(self, prices: List[int]) -> int:
return sum(max(0, b - a) for a, b in zip(prices, prices[1:]))
assert Solution().maxProfit([7, 1, 5, 3, 6, 4]) == 7
assert Solution().maxProfit([1, 2, 3, 4, 5]) == 4
class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
for (int i = 1; i < prices.length; i++) profit += Math.max(0, prices[i] - prices[i - 1]);
return profit;
}
}
func maxProfit(prices []int) int {
total := 0
for i := 1; i < len(prices); i++ {
total += max(0, prices[i]-prices[i-1]) // collect every rise
}
return total
}