Diwali Offer!Flat 20% OFF
Enroll Now
PrakalpanaLive online tech training

194. Best Time to Buy and Sell Stock II

MediumDay 57 of 60Greedy & Intervals

You are given prices, where prices[i] is a stock's price on day i. You may buy and sell as many times as you like, but you can hold at most one share at a time (you may sell and buy again on the same day). Return the maximum total profit.

Example 1
Input: prices = [7,1,5,3,6,4]
Output: 7
Buy at 1 and sell at 5 (profit 4), then buy at 3 and sell at 6 (profit 3).
Example 2
Input: prices = [1,2,3,4,5]
Output: 4
Buy at 1 and sell at 5. This equals the sum of the daily gains 1 + 1 + 1 + 1.
Constraints
  • 1 <= prices.length <= 3 * 10^4
  • 0 <= prices[i] <= 10^4
Hints
Frequently asked at: Amazon, Microsoft, Google, Bloomberg
Ctrl + Enter runs the examples

Not sure what to learn next?

A 1-on-1 session with an industry mentor and a roadmap built for you. How it works

  1. 1Discuss your goals
  2. 2Get a personal plan
  3. 3Start learning
Book for β‚Ή200/ 30 min