Problem Description
Given two integer arrays a (of size 4) and b (of size at least 4), choose 4 indices i0, i1, i2, and i3 from b (with i0 < i1 < i2 < i3) so that the score computed as:
a[0] * b[i0] + a[1] * b[i1] + a[2] * b[i2] + a[3] * b[i3]
is maximized. Return the maximum score achievable.
Key Insights
- The array a has a fixed size (4) and the order of selection in b matters (increasing indices).
- A dynamic programming (DP) approach can be applied where we progressively pick elements from b.
- We use DP to maintain the best achievable score after choosing k elements (k = 0..4), updating in order.
- The DP state update is done in reverse order for each element in b to avoid overwriting states needed for the next update.
- Time complexity is O(n) since we iterate through b only once, and there are only 4 stages.
Space and Time Complexity
Time Complexity: O(n), where n is the length of b
Space Complexity: O(1), as we use only a fixed-size DP array with 5 elements
Solution
We solve the problem using dynamic programming. We maintain a DP array dp of size 5 (indexes 0 to 4) where dp[k] represents the maximum achievable score by selecting k elements from b corresponding to the first k elements of a. We initialize dp[0] = 0 (no selections gives 0 score) and dp[1..4] with very small numbers (e.g., negative infinity) to indicate unachievable states initially.
Then, for each element b[i] in b, we update the dp array in reverse order—from dp[4] down to dp[1]. The reason for reverse iteration is to ensure that when calculating dp[k] we use the dp[k-1] value from the same iteration round (from previously considered elements only). The state transition is:
dp[k] = max(dp[k], dp[k-1] + a[k-1] * b[i])
After processing all elements, dp[4] will hold the maximum achievable score. This approach efficiently ensures the order requirement on b and correctly pairs with the fixed order in a.