FastPrepBest Time to Buy and Sell Stock

Best Time to Buy and Sell Stock

Headlands Technologies logoHeadlands Technologies● EasyFULLTIMEPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

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

Choose at most one day to buy one share and a later day to sell it. Return the maximum profit you can earn. If no profitable transaction exists, return 0.

Function

maxProfit(prices: int[]) → int

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 = [2,4,1,8]return = 7

Buying at price 1 and selling at price 8 beats the earlier profit of 2.

Constraints

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

More Headlands Technologies problems

See Headlands Technologies hiring insights
public int maxProfit(int[] prices) {
    // write your code here
}
prices[7,1,5,3,6,4]
expected5
Checking account…