This approach involves using dynamic programming to keep track of the maximum scores obtainable by choosing elements from either the start or the end of the nums array during each step of the operations defined by the multipliers array. We maintain a 2D DP table where dp[i][j] represents the maximum score obtained by using the first (i + j) elements from nums, where i elements have been chosen from the start, and j elements have been chosen from the end.
Time Complexity: O(m^2), where m is the length of the multipliers array, because we're filling an m x m DP table.
Space Complexity: O(m^2) due to the storage requirements of the m x m DP table.
1#include<vector>
2#include<algorithm>
3using namespace std;
4
5int maximumScore(vector<int>& nums, vector<int>& multipliers) {
6 int n = nums.size(), m = multipliers.size();
7 vector<vector<int>> dp(m + 1, vector<int>(m + 1, 0));
8 for (int i = m - 1; i >= 0; --i) {
9 for (int left = i; left >= 0; --left) {
10 dp[i][left] = max(
11 multipliers[i] * nums[left] + dp[i + 1][left + 1],
12 multipliers[i] * nums[n - 1 - (i - left)] + dp[i + 1][left]
13 );
14 }
15 }
16 return dp[0][0];
17}
The implementation initializes a 2D DP vector of size (m+1) x (m+1), which we fill backwards based on our choices of picking from the start or end of the nums
array. The result will be found in dp[0][0]
after processing all the operations.
This approach uses a simpler greedy strategy to try and choose the best possible option at each step, based on examining both the start and end of the nums array for potential scores. It evaluates which element, when multiplied with the current multiplier, gives the maximum increase in the score and selects that iteratively through all operations.
Time Complexity: O(m), where m is the number of operations.
Space Complexity: O(1), utilizing constant space regardless of input size.
1def maximum_score(nums, multipliers):
2 left, right = 0, len(nums) - 1
3 score = 0
4 for multiplier in multipliers:
5 if multiplier * nums[left] >= multiplier * nums[right]:
6 score += multiplier * nums[left]
7 left += 1
8 else:
9 score += multiplier * nums[right]
10 right -= 1
11 return score
The function computes the maximum playable score using a greedy method that goes through each multiplier in the multipliers array. At each step, it determines whether picking the starting element or the ending element in the nums array yields a better score and then opts for that choice until all operations are exhausted.