Best Time to Buy and Sell Stock II
Pattern: Stock buy and sell
With unlimited transactions (holding one share at a time), the most profit is the sum of every rise from one day to the next.
The problem
Return the most profit from any number of buy-then-sell transactions, holding at most one share at a time.
Think first
- Can a long rise be split into daily rises?
- Is a fall ever worth holding through?
- What is the DP version?
Hints
Brute force, and why it fails
Try every set of transactions: exponential.
The key insight
Every rise can be captured and every fall avoided, so the answer is the sum of positive daily differences.
Dry run
[7, 1, 5, 3, 6, 4]. Rises: 1 to 5 (4) and 3 to 6 (3).
Step 1 of 2
The plan
profit = sum of max(0, p[i] - p[i-1])
Complexity
- Time
O(n)- Space
O(1)
One pass.
Edge cases
- Falling prices: 0.
- Rising prices: last - first.
- One day: 0.
I've built my logic, show the code
Java
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]; // take every rise
return profit;
}
}C++
class Solution {
public:
int maxProfit(vector<int>& prices) {
int profit = 0;
for (size_t i = 1; i < prices.size(); i++)
if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1]; // take every rise
return profit;
}
};Python
class Solution:
def maxProfit(self, prices: list[int]) -> int:
return sum(max(0, b - a) for a, b in zip(prices, prices[1:])) # take every riseCommon mistakes
- Looking for the single best transaction.
- Counting falls.