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

2. Best Time to Buy and Sell Stock

EasyDay 1 of 60Arrays & Hashing

You are given prices, where prices[i] is the price of a stock on day i. You may buy on one day and sell on a later day, at most once. Return the largest profit you can make, or 0 if no trade makes money.

Example 1
Input: prices = [7,1,5,3,6,4]
Output: 5
Buy on day 1 at price 1 and sell on day 4 at price 6, profit 6 - 1 = 5.
Example 2
Input: prices = [7,6,4,3,1]
Output: 0
Prices only fall, so the best choice is not to trade.
Constraints
  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4
Hints
Frequently asked at: Amazon, Microsoft, Google, Goldman Sachs, Flipkart, Accenture
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