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). The arrays are 1-indexed. Now our initial score is 0. We want to perform exactly m operations. On the ith operation (1-indexed), we will −

  • Select one value from x from either the start or the end of the nums.

  • Add multipliers[i] * x to the score.

  • Remove x from the array nums.

We have to find the maximum score after performing m operations.

So, if the input is like nums = [5,10,15], multipliers = [5,3,2], then the output will be 115 because we can take 15 then multiply it with 5 to get 5*15 = 75, then 10*3 = 30, so total is 75+30 = 105 and finally 5*2 = 10, so total 105+10 = 115.

To solve this, we will follow these steps −

  • n := size of nums, m := size multipliers

  • dp := One 2D array of size m x (m+1) and fill with 0

  • for i in reverse the list range 0 to m - 1, do

    • for j in range i to m - 1, do

      • k := i + m - j - 1

      • dp[i, j] = maximum of (nums[i] * multipliers[k] + dp[i+1, j]) and (nums[j-m+n] * multipliers[k] + dp[i, j-1])

  • return last element of dp[0]

Example

Let us see the following implementation to get better understanding −

def solve(nums, multipliers):
   n, m = len(nums), len(multipliers)
   dp = [[0]*m for _ in range(m+1)]

   for i in reversed(range(m)):
      for j in range(i, m):
         k = i + m - j - 1
         dp[i][j] = max(nums[i] * multipliers[k] + dp[i+1][j], nums[j-m+n] * multipliers[k] + dp[i][j-1])

   return dp[0][-1]

nums = [5,10,15]
multipliers = [5,3,2]
print(solve(nums, multipliers))

Input

[5,10,15], [5,3,2]

Output

115

Updated on: 06-Oct-2021

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements