FastPrepBest Time to Buy and Sell Stock
Problem · Array

Best Time to Buy and Sell Stock

Learn this problem
EasyFlexTrade logoFlexTradeFULLTIMEOA

Problem statement

You are given an integer array prices, where prices[i] is the price of one share on day i.

Choose at most one day to buy and one later day to sell. Return the maximum profit. If no profitable transaction exists, return 0.

Function

maxProfit(prices: int[]) → long

Examples

Example 1

prices = [7,1,5,3,6,4]return = 5

Buy at price 1 and sell later at price 6 for profit 5.

Example 2

prices = [7,6,4,3,1]return = 0

Every later price is lower, so the best choice is not to trade.

Example 3

prices = [3,3,5,0,0,3,1,4]return = 4

Buy at a price of 0 and sell later at 4.

Constraints

  • 1 <= prices.length <= 200000
  • 0 <= prices[i] <= 10^9

More FlexTrade problems

drafts saved locally
public long maxProfit(int[] prices) {
  // Write your code here.
}
prices[7,1,5,3,6,4]
expected5
checking account