Best Time to Buy and Sell Stock II
This problem allows for buying and selling on the same day, and you can make as many transactions as you like. You will profit from buying and selling whenever the price of the stock increases from one day to the next.
Here’s the approach to this problem:
- Initialization: Initialize a variable
max_profit
to store the maximum profit. Set it to 0 initially. - Iteration: Iterate through the
prices
array from the second element onwards.- For each price, check if it is greater than the previous day’s price.
- If so, add the difference between the current price and the previous day’s price to
max_profit
.
- Result:
max_profit
holds the maximum profit that can be achieved.
Here’s the code:
|
|
Key Takeaways:
- The code identifies opportunities for profit by looking at the increase in price from one day to the next.
- By buying and selling on the days when the price increases, you can achieve the maximum profit.
- The time complexity of this solution is (O(n)), where (n) is the length of the
prices
array. - The space complexity is (O(1)), as we only use a constant amount of extra space.
You may have few transactions to maximize the profit. We don’t have to maximize the transactions. We have to maximize the profit.
If all numbers are decreasing, you cannot make any profit. If you cannot sell at a profit, return 0. Cannot return negative.
|
|
Run a loop and keep checking If i is less than i+1 Calculate the difference between those two values (complete the transaction - profit) Accumulate the profit in a sum variable 0 1 2 3 4 5 [7,1,5,3,6,4]
Scenarios to Buy/Sell 1-5 3-6
Greedy approach
We can have a profit variable intialized to 0
|
|
Time: O(N) Space: O(1)
|
|