With one stock transaction, I need the best buying day and a later selling day. With unlimited transactions, I can collect every rise between consecutive days.
The constraint
The input is an array prices, where prices[i] is the stock price on day i. Buying and selling on the same day is allowed, but I can hold only one stock at a time. The goal is the maximum total profit.
When prices rise on consecutive days, a sale and a new purchase at the same price preserve the total profit. For example, consider the gain from day 1 to day 2, then from day 2 to day 3. Their sum equals the gain from day 1 to day 3. Thus, the algorithm only needs the positive differences between adjacent prices.
A price decrease adds no profit. Splitting a rising sequence into several transactions keeps the same gain without holding more than one stock.
For [7, 1, 5, 3, 6, 4], the increases are 1 → 5 and 3 → 6, so the total profit is 4 + 3 = 7.
Greedy implementations
function maxProfit(prices) {
let maxProfit = 0;
// Check each day compared to the previous day
for (let i = 1; i < prices.length; i++) {
// If price increased, add that profit
if (prices[i] > prices[i - 1]) {
maxProfit += prices[i] - prices[i - 1];
}
}
return maxProfit;
}
// Example usage:
const prices = [7, 1, 5, 3, 6, 4];
console.log(maxProfit(prices)); // Output: 7
For the same example, the adjacent changes are:
- Day 0 to Day 1: 7 → 1 (decrease, no profit)
- Day 1 to Day 2: 1 → 5 (increase! profit = 4)
- Day 2 to Day 3: 5 → 3 (decrease, no profit)
- Day 3 to Day 4: 3 → 6 (increase! profit = 3)
- Day 4 to Day 5: 6 → 4 (decrease, no profit)
The total profit is 4 + 3 = 7.
Every positive adjacent difference belongs to some increasing run. Adding the differences in a run is equal to buying at its first price and selling at its last price. Negative differences cannot improve the result, so skipping them is safe. The scan thus produces the maximum profit in one pass.
public class StockProfit {
public static int maxProfit(int[] prices) {
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
maxProfit += prices[i] - prices[i - 1];
}
}
return maxProfit;
}
public static void main(String[] args) {
int[] prices = {7, 1, 5, 3, 6, 4};
System.out.println(maxProfit(prices)); // Output: 7
}
}
Complexity and reusable pattern
The scan takes O(n) time and O(1) extra space. It needs only the previous price and the accumulated profit.
This works because the problem allows unlimited transactions without fees or a cooldown. Those constraints would change which price increases can be collected.

Loading comments...