Best Time to Buy and Sell Stock II - Complete Solution Guide
Best Time to Buy and Sell Stock II is LeetCode problem 122, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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 sell and buy the stock multiple times on the same day , ensuring you never hold than one share of the stock. 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
Detailed Explanation
The problem requires you to find the maximum profit you can make by buying and selling a stock multiple times, given an array `prices` where `prices[i]` is the price of the stock on day `i`. You can buy and sell on the same day, but you can only hold one share of the stock at a time. The goal is to maximize the total profit from these transactions.
Solution Approach
The solution uses a greedy approach. It iterates through the `prices` array and checks if the current day's price is higher than the previous day's price. If it is, it adds the difference between the two prices to the `total_profit`. This approach is based on the principle that we should buy when the price is low and sell when the price is high, and we can repeat this process as many times as possible.
Step-by-Step Algorithm
- Step 1: Initialize `total_profit` to 0.
- Step 2: Iterate through the `prices` array starting from the second day (index 1).
- Step 3: For each day, compare the price with the previous day's price.
- Step 4: If the current day's price is greater than the previous day's price, calculate the difference and add it to `total_profit`.
- Step 5: After iterating through all the days, return `total_profit`.
Key Insights
- Insight 1: The greedy approach works here because we can make independent decisions on each day. If the price tomorrow is higher than today, we buy today and sell tomorrow to make a profit.
- Insight 2: We don't need to keep track of buy and sell days specifically. We just need to accumulate the profit whenever there's an increase in price from one day to the next.
- Insight 3: The problem allows for multiple transactions within the same day, which simplifies the logic to only consider increasing price differences.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: Array, Dynamic Programming, Greedy.
Companies
Asked at: Agoda, CTC, Capital One, Citadel, DE Shaw, Deutsche Bank, Geico, Goldman Sachs, Groww, Infosys, Intel, J.P. Morgan, Media.net, Nike, Paytm, PhonePe, Qualcomm, Rakuten, Salesforce, TikTok, Uber, Walmart Labs, Wells Fargo, Yahoo, Yandex, Zoho, eBay, tcs.