Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find maximum score from performing multiplication operations in Python
Suppose we have two arrays nums and multipliers of size n and m respectively (n >= m). We want to perform exactly m operations to achieve the maximum score. Our initial score is 0.
In each operation, we can:
Select one value
xfrom either the start or the end of thenumsarrayAdd
multipliers[i] * xto the scoreRemove
xfrom the arraynums
We need to find the maximum score after performing m operations.
Example
If the input is nums = [5,10,15] and multipliers = [5,3,2], then the output will be 115:
Take 15 from end: 15 * 5 = 75, remaining nums = [5,10]
Take 10 from end: 10 * 3 = 30, remaining nums = [5]
Take 5 from start: 5 * 2 = 10, remaining nums = []
Total score: 75 + 30 + 10 = 115
Approach Using Dynamic Programming
We use dynamic programming to solve this problem. The key insight is to track how many elements we've taken from the left and right sides of the array.
The algorithm follows these steps:
Create a 2D DP array where
dp[i][j]represents the maximum score when we've takenielements from the left andjelements from the rightFor each operation, we can either take from the left or right end
Choose the option that gives the maximum score
Implementation
def solve(nums, multipliers):
n, m = len(nums), len(multipliers)
# dp[i][j] = max score taking i from left, j from right
dp = [[0] * (m + 1) for _ in range(m + 1)]
for op in range(m - 1, -1, -1): # operations in reverse
for left in range(op + 1): # elements taken from left
right = op - left # elements taken from right
# Option 1: take from left
left_score = nums[left] * multipliers[op] + dp[left + 1][right]
# Option 2: take from right
right_score = nums[n - 1 - right] * multipliers[op] + dp[left][right + 1]
dp[left][right] = max(left_score, right_score)
return dp[0][0]
# Test the function
nums = [5, 10, 15]
multipliers = [5, 3, 2]
result = solve(nums, multipliers)
print(f"Maximum score: {result}")
Maximum score: 115
How It Works
The dynamic programming solution works backwards from the last operation:
dp[left][right]stores the maximum score when we've takenleftelements from the start andrightelements from the endFor each state, we try both options (take from left or right) and choose the maximum
The answer is stored in
dp[0][0]which represents the maximum score starting with no elements taken
Time and Space Complexity
Time Complexity: O(m²) where m is the length of multipliers array
Space Complexity: O(m²) for the DP table
Conclusion
This dynamic programming approach efficiently finds the maximum score by considering all possible combinations of taking elements from either end of the array. The key insight is to work backwards and store optimal solutions for subproblems.
