Best Time to Buy and Sell Stock II
Medium
Topics
You are given an array prices where prices[i] is the price of a stock on day i. You may buy and sell as many times as you like (but hold at most one share at a time). Return the maximum profit.
Example 1
Input: prices = [7,1,5,3,6,4] Output: 7
Example 2
Input: prices = [1,2,3,4,5] Output: 4
Constraints
- 1 <= prices.length <= 3*10^4
- 0 <= prices[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
Unlimited transactions, and you may sell and rebuy on the same day. That freedom makes the problem much easier than it looks, and the reason is worth stating properly.
Any profitable multi-day hold decomposes into consecutive daily gains: buying at day i and selling at day j yields prices[j] - prices[i], which telescopes into the sum of every daily change in between. So a long hold through a rising stretch earns exactly the same as buying and selling each day within it. Since we can skip the negative days entirely, the maximum is simply the sum of every positive daily change.
prices 1 5 3 6
deltas +4 -2 +3
take the positives: 4 + 3 = 7
which is the same as (5-1) + (6-3)No state machine, no DP — though the four-state DP from the "at most two transactions" variant also solves this with the transaction cap removed, and that is the answer if a transaction fee is added later.
Approach
- Sum
prices[i] - prices[i-1]whenever it is positive.
Dry Run
prices = [7,1,5,3,6,4]
7->1 -6 skip
1->5 +4 profit 4
5->3 -2 skip
3->6 +3 profit 7
6->4 -2 skip
answer 7 (buy at 1 sell at 5, buy at 3 sell at 6)Complexity
- Time — O(n): one pass.
- Space — O(1): one accumulator.
Common Pitfalls
- Trying to identify actual buy and sell days. The sum of positive deltas gives the right total without naming them, and reconstructing the trades is a separate question.
- Looking for the single largest rise. That solves the one-transaction variant instead.
- Adding negative deltas, which is equivalent to being forced to hold through a decline.
- Assuming a transaction fee can be handled by this greedy. It cannot — a fee makes the decomposition invalid, because splitting one long hold into many trades then pays the fee repeatedly, and the problem becomes the state-machine DP.
Full Solution — all languages
class Solution:
def maxProfit(self, nums):
profit = 0
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
profit += nums[i] - nums[i - 1]
return profitimport java.util.*;
class Solution {
public int maxProfit(int[] nums) {
int profit = 0;
for (int i = 1; i < nums.length; i++) if (nums[i] > nums[i - 1]) profit += nums[i] - nums[i - 1];
return profit;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxProfit(vector<int>& nums) {
int profit = 0;
for (int i = 1; i < (int)nums.size(); i++) if (nums[i] > nums[i - 1]) profit += nums[i] - nums[i - 1];
return profit;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var maxProfit = function(nums) {
let profit = 0;
for (let i = 1; i < nums.length; i++) if (nums[i] > nums[i - 1]) profit += nums[i] - nums[i - 1];
return profit;
};