Best time to buy and sell a stock
Coding problemEasy-MediumAsked in: Adobe, Amazon, Google, Infosys, Microsoft, TCS
You are given the price of a stock on each day, in order. You may buy one share on one day and sell it on a later day. Return the largest profit you can make.
If no profit is possible (prices only fall, or there are fewer than two days), return 0.
Examples
Example 1
Input: prices = [7,1,5,3,6,4]
Output: 5
Buy at 1 on day 2 and sell at 6 on day 5.
Example 2
Input: prices = [7,6,4,3,1]
Output: 0
Example 3
Input: prices = [2,4,1]
Output: 2
Selling must come after buying, so buying at 1 does not help.
Constraints
- The list holds between 0 and 300,000 prices
- Each price is between 0 and 10,000
Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.
Run your code to see the results here. Ctrl or Cmd + Enter runs; add Shift to submit.