Given an array of daily stock prices, find the maximum profit achievable by completing as many non-overlapping buy-sell transactions as you like.
Video coming soon
We're producing a video walkthrough — check back soon.
Given an array of daily stock prices, find the maximum profit achievable by completing as many non-overlapping buy-sell transactions as you like.
The direct sequel to the single-transaction version — the same array, but the constraint changes from once to as many times as you want, and the optimal strategy pivots from tracking a minimum to summing every upward step.
When a problem removes a 'do this only once' restriction and allows unlimited repeats with no cooldown or fee, check whether the optimal answer decomposes into every individual profitable move — that's the greedy signal.
Walk the array once comparing each day to the day before it. Whenever prices[i] > prices[i-1], add that difference to a running profit total — this is equivalent to buying the day before and selling the day of every single upward step, which always matches or beats any coarser buy/sell pairing over the same climb. Days where the price falls or stays flat contribute nothing. No transaction limit needs to be tracked explicitly, because summing every positive step already accounts for as many transactions as the price sequence naturally supports.
class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
profit += prices[i] - prices[i - 1];
}
}
return profit;
}
}