FastPrepBest Time to Buy and Sell Stock II

Best Time to Buy and Sell Stock II

Kotak Mahindra Bank logoKotak Mahindra Bank● MediumFULLTIMEONSITE 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 start with no share. On each day you may buy one share, sell the share you hold, or do both. You can hold at most one share at a time, but you may make as many trades as you like.

Return the largest total profit you can make.

Function

maxProfit(prices: int[]) → int

Examples

Example 1

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

Buy at 1 on day 1 and sell at 5 on day 2, for a profit of 4. Then buy at 3 on day 3 and sell at 6 on day 4, for a profit of 3. The total is 4 + 3 = 7.

Example 2

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

Buy at 1 on day 0 and sell at 5 on day 4, for a profit of 4. Selling and buying again every day gives the same total of 4.

Example 3

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

The price falls every day, so no trade can make money. The best choice is not to trade, which gives 0.

Constraints

  • 1 <= prices.length <= 3 * 10^4
  • 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…