Problem

Maximum Stock Profit With Time Gap

Learn this problem
Toast logoToastFULLTIMEPHONE SCREEN

Problem statement

You are given the stock prices for one day in chronological order. Each element represents the price at one second.

You may buy once and sell once. The sell time must be at least 5 seconds after the buy time. In other words, if you buy at index i and sell at index j, then j - i >= 5.

Return the maximum profit possible. If no profitable trade exists, return 0.

Function

maximumProfitWithTimeGap(prices: long[]) → long

Examples

Example 1

prices = [10,8,7,12,9,15]return = 5

Buy at index 0 for 10 and sell at index 5 for 15. Buying at index 2 and selling at index 5 is not allowed because the gap is only 3 seconds.

Example 2

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

The best valid trade buys at index 0 and sells at index 5.

Example 3

prices = [9,8,7,6,5,4]return = 0

No valid buy/sell pair gives a positive profit.

Constraints

  • prices.length >= 1
  • Each adjacent pair of prices is one second apart.
drafts saved locally
public long maximumProfitWithTimeGap(long[] prices) {
  // write your code here
}
prices[10,8,7,12,9,15]
expected5
checking account