Program to find maximum subarray min-product in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array nums, we have to find the maximum min-product of each non-empty subarray of nums. Since the answer can be big enough, return it in modulo 10^9+7. The min-product of the array is equal to the minimum value in the array multiplied by the sum of the array. So if we have an array is like [4,3,6] (minimum value is 3) has a min-product of 3*(4+3+6) = 3*13 = 39.

So, if the input is like nums = [2,3,4,3], then the output will be 30 because we can get subarray [3,4,3] for maximizing the result, so 3*(3+4+3) = 3*10 = 30.

To solve this, we will follow these steps −

  • m := 10^9+7

  • stack := a new stack

  • rsum := 0, res := 0

  • insert 0 at the end of nums

  • for each index i and value v in nums, do

    • while stack is not empty and nums[index of top of stack] >= v, do

      • index, val) := top of stack and pop it from stack

      • arrSum:= rsum

      • if stack not empty, then

        • arrSum:= rsum - value of top of stack

      • res:= maximum of res and (nums[index]*arrSum)

    • rsum := rsum + v

    • push (i, rsum) at the end of stack

  • return res mod m

Example

Let us see the following implementation to get better understanding −

def solve(nums):
   m = int(1e9+7)
   stack = []
   rsum = 0
   res = 0

   nums.append(0)

   for i, v in enumerate(nums):
      while stack and nums[stack[-1][0]] >= v:
         index, _ = stack.pop()

         arrSum=rsum

         if stack:
            arrSum=rsum-stack[-1][1]

         res=max(res, nums[index]*arrSum)

      rsum += v
      stack.append((i, rsum))

   return res % m

nums = [2,3,4,3]
print(solve(nums))

Input

[2,3,4,3]

Output

30
raja
Published on 08-Oct-2021 07:18:59
Advertisements