Problem
You are given two 0-indexed integer arrays nums
and multipliers
of size n
and m
respectively, where n >= m
.
You begin with a score of 0
. You want to perform exactly m
operations. On the ith
operation (0-indexed) you will:
- Choose one integer
x
from either the start or the end of the arraynums
. - Add
multipliers[i] * x
to your score.- Note that
multipliers[0]
corresponds to the first operation,multipliers[1]
to the second operation, and so on.
- Note that
- Remove
x
fromnums
.
Return the maximum score after performing m
operations.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 – Dynamic Programming 1
Intuition
The problem asks us to maximize the score by picking elements from either end of the array for each operation. Since each choice affects future choices, dynamic programming is ideal to explore all possibilities efficiently.
Approach
- Use a DP table where
dp[i][l]
represents the maximum score afteri
operations, having pickedl
elements from the left. - For each operation, either pick from the left or right and update the DP table accordingly.
- The right index is determined by the number of picks from the left and the current operation.
- The answer is the maximum value after all operations.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m^2)
, since for each operation and left pick, we fill the DP table. - 🧺 Space complexity:
O(m^2)
, for the DP table.