Menu
CoddyTech

Best Time to Buy and Sell Stock

EasyGreedypython iconjava iconcpp iconc iconjs icon+10

You get a list prices, where prices[i] is the price of one stock on day i. You may buy one share on one day and sell it on a later day. Return the largest profit you can make, or 0 when every possible trade loses money.

Function

maxProfit(prices: integer-array) → integer
pricesinteger-array
the stock's price on each day, in order
Returnsinteger
the largest profit from one buy and a later sale, or 0

Constraints

  • 1 ≤ prices.length ≤ 105
  • 0 ≤ prices[i] ≤ 104
  • You make at most one trade, and you sell on a later day than you buy.

Examples

Input
prices = [7, 2, 5, 9, 1, 4]
Output
7
Explanation
Buy on day 1 at 2 and sell on day 3 at 9 for a profit of 7. The cheapest price, 1 on day 4, comes after the 9, so the best sale after it earns only 3.
challenge icon

Follow-up

What if you may make as many trades as you like, while holding at most one share at a time?

Reset code
def maxProfit(prices):
    # Write code here

Test #1

Test #2

Argument

prices = [7, 2, 5, 9, 1, 4]

Expected Output

7