Profit From Multiple Stock Trades
Problem
Given a daily price series, you can buy and sell as often as you like, holding at most one share at a time. What is the maximum total profit? The greedy answer: sum every positive day-over-day climb. Any longer winning streak from a low to a high decomposes exactly into those single-day gains, so capturing every up-day is optimal.
Input
prices = [7, 1, 5, 3, 6, 4]Output
7Buy at 1, sell at 5 (+4). Buy at 3, sell at 6 (+3). Total 7 — equal to the sum of (5−1) + (6−3) = (5−1) is split into (1→2 etc). Equivalently, sum positive deltas: (5−1)+(3−5 skip)+(6−3)+(4−6 skip) = 4 + 3.
def max_profit(prices):
profit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
profit += prices[i] - prices[i - 1]
return profit
function maxProfit(prices) {
let profit = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
profit += prices[i] - prices[i - 1];
}
}
return profit;
}
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;
}
}
int maxProfit(vector<int>& prices) {
int profit = 0;
for (int i = 1; i < prices.size(); i++) {
if (prices[i] > prices[i - 1]) {
profit += prices[i] - prices[i - 1];
}
}
return profit;
}