Problem · Array

Stock Maximum Profit

Learn this problem
HardIBM logoIBMFULLTIMEOA
See IBM hiring insights

Problem statement

Given arrays price and profit of equal length, choose three days with indices i < j < k such that:

price[i] < price[j] < price[k]

Maximize profit[i] + profit[j] + profit[k]. Return the maximum possible total profit, or -1 if no valid triplet exists.

Function

getMaxProfit(price: int[], profit: int[]) → long

Examples

Example 1

price = [2, 3, 1, 5, 9]profit = [1, 2, 6, 1, 5]return = 12

Choose indices (2, 3, 4) using 0-based indexing. The prices are 1 < 5 < 9 and the total profit is 6 + 1 + 5 = 12.

Example 2

price = [4, 3, 2, 1]profit = [4, 3, 2, 1]return = -1

The prices are strictly decreasing, so no valid triplet exists.

Constraints

  • 1 ≤ price.length = profit.length ≤ 4000
  • 1 ≤ price[i] ≤ 10^9
  • 1 ≤ profit[i] ≤ 10^9

More IBM problems

drafts saved locally
public long getMaxProfit(int[] price, int[] profit) {
    // Write your code here
}
price[2, 3, 1, 5, 9]
profit[1, 2, 6, 1, 5]
expected12
checking account