FastPrepBest Time to Buy and Sell Stock

Best Time to Buy and Sell Stock

Kotak Mahindra Bank logoKotak Mahindra Bank● EasyFULLTIMEONSITE INTERVIEW

Problem statement

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

You may make at most one trade: buy one share on one day, then sell it on a later day. Return the largest profit you can make. If no trade makes money, return 0.

Function

maxProfit(prices: int[]) → int

Examples

Example 1

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

Buy on day 1, when the price is 1, and sell on day 4, when the price is 6. The profit is 6 - 1 = 5.

The price 7 on day 0 is higher, but it comes before day 1, so you cannot sell there after buying at 1.

Example 2

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

The price falls every day, so every possible trade loses money. The best choice is not to trade, which gives 0.

Example 3

prices = [2,4,1]return = 2

The lowest price, 1, is on the last day, so there is no later day to sell it. The best trade is to buy at 2 on day 0 and sell at 4 on day 1, for a profit of 2.

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4

More Kotak Mahindra Bank problems

See Kotak Mahindra Bank hiring insights
Saved
public int maxProfit(int[] prices) {
    // Write your code here.
}
Checking account…