Problem · Array

Maximize Profit

Learn this problem
MediumTiktokOA
See Tiktok hiring insights

Problem statement

You are given arrays rates and strategy. The value rates[i] is the currency price on day i, while strategy[i] is:

  • -1 to buy,
  • 0 to hold, or
  • 1 to sell.

The profit of a strategy is sum(strategy[i] * rates[i]).

You must modify exactly one range of k consecutive positions, where k is even:

  1. Set the first half of the chosen range to 0.
  2. Set the second half of the chosen range to 1.

Choose the range that maximizes the final profit and return that maximum profit.

Function

maxProfit(strategy: int[], rates: int[], k: int) → int

Examples

Example 1

strategy = [1, 0, 0, -1]rates = [2, 3, 4, 5]k = 4return = 9

The only length-4 range is the whole array. It changes the strategy to [0, 0, 1, 1], giving profit 4 + 5 = 9.

Constraints

  • strategy.length = rates.length
  • Every strategy[i] is -1, 0, or 1.
  • Every rates[i] is a non-negative 32-bit integer.
  • 2 <= k <= strategy.length
  • k is even.
  • The absolute value of every possible final profit fits in a signed 32-bit integer.

More Tiktok problems

drafts saved locally
public int maxProfit(int[] strategy, int[] rates, int k) {
  // write your code here
}
strategy[1, 0, 0, -1]
rates[2, 3, 4, 5]
k4
expected9
checking account