Problem
You are given two integer arrays nums
and multipliers
of size n
and m
respectively, where n≥m
. The arrays are 1-indexed.
You begin with a score of 0
. You want to perform exactly m
operations. On the iᵗʰ
operation (1-indexed), you will:
- Choose one integer
x
from either the start or the end of the arraynums
. - Add
multipliers[i] * x
to your score. - Remove
x
from the arraynums
.
Return the maximum score after performing m
operations.
Example 1
Input:
nums = [1,2,3]
,multipliers = [3,2,1]
Output:14
Explanation: An optimal solution is as follows:
- Choose from the end, [1,2,3], adding
3*3 = 9
to the score.- Choose from the end, [1,2], adding
2*2 = 4
to the score.- Choose from the end, [1], adding
1*1 = 1
to the score.The total score is
9+4+1 = 14
Example 2
Input:
nums = [-5,-3,-3,-2,7,1]
,multipliers = [-10,-5,3,4,6]
Output:102
Explanation: An optimal solution is as follows:
- Choose from the start, [-5,-3,-3,-2,7,1], adding
-5 * -10 = 50
to the score.- Choose from the start, [-3,-3,-2,7,1], adding
-3 * -5 = 15
to the score.- Choose from the start, [-3,-2,7,1], adding
-3 * 3 = -9
to the score.- Choose from the end , [-2,7,1], adding
1 * 4 = 4
to the score.- Choose from the end , [-2,7], adding
7 * 6 = 42
to the score.The total score is
50 + 15 - 9 + 4 + 42 = 102
.
My Approach
I tried to solve it using Dynamic Programming and formed following Bellman Equation.
$X[i][j]$ stores the maximum possible score after we have done $i$ total operations and used $j$ numbers from the left/start side. The index of the rightmost element can be calculated from $n-1-(i-j)$. For purpose of formulation
multipliers
has been renamed to $M$ whilenums
to $N$ $$ X[i][j] = \begin{cases} \text{max}\bigg((M[i]\cdot N[j]) + X[i+1][j+1],\\\quad\quad\quad(M[i]\cdot N[n-1-(i-j)]) + X[i+1][j]\bigg), & \text{if $i \neq m$ } \\[2ex] 0, & \text{if $i=m$} \end{cases} $$
We essentially choose the maximum on choosing from left or right. If we choose left, next operation will occur at $[i+1][j+1]$, else next operation will occur at $[i+1][j]$.
On writing code for the same, the approach worked fine 👍🏻
Question
Why Greedy Approach is failing here? On Going Greedy in Example 2,
- [-5,-3,-3,-2,7,1], from
50 vs -10
, choose50
, henceleft
- [-3,-3,-2,7,1], from
15 vs -5
, choose15
, henceleft
- [-3,-2,7,1], from
-9 vs 3
, choose3
, henceright
- [-3,-2,7], from
-12 vs 28
, choose28
, henceright
- [-3,-2], from
-18 vs -12
, choose-12
, henceright
The total score is
50 + 15 + 3 + 28 - 12 = 84
, which isn't optimal.
Is there a formal proof using eXchange Argument [Although the link suggests that To show that an algorithm A does not solve a problem it is sufficient to exhibit one input on which A does not produce an acceptable output] or Greedy Stays Ahead Approach$\color{red}{?}$
Any hint would be of great help. Thanks!