Best Time To Buy And Sell Stock Ii Problem
Description
LeetCode Problem 122.
You are given an integer array prices where prices[i] is the price of a given stock on the i^th day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
Example 2:
Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.
Example 3:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
Constraints:
- 1 <= prices.length <= 3 * 10^4
- 0 <= prices[i] <= 10^4
Solution
Approach: Sum Every Price Rise
With no limit on the number of transactions, we can collect every increase in price. Any trade that buys on day i and sells on day j earns prices[j] - prices[i], which equals the sum of the day-to-day changes in between:
(prices[i+1] - prices[i]) + (prices[i+2] - prices[i+1]) + ... + (prices[j] - prices[j-1]).
Leaving out the negative changes can only make that sum larger, and holding over exactly the rising days is a valid plan (buy before a rise, sell at its end; buying and selling on the same day is allowed). So the answer is:
sum of max(0, prices[d] - prices[d - 1]) for every day d from 1 to n - 1.
For [7, 1, 5, 3, 6, 4] the rises are 1 → 5 (+4) and 3 → 6 (+3), for a total of 7. For [1, 2, 3, 4, 5] the four rises of +1 add up to 4, the same as buying on day 1 and selling on day 5.
Complexity: O(n) time and O(1) space, where n is the length of prices.
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
for day in range(1, len(prices)):
rise = prices[day] - prices[day - 1]
if rise > 0: # hold the stock over every day the price goes up
profit += rise
return profit
Now write it from memory
Close the write-up and solve it yourself against the tests.