Program to find out the sum of the maximum subarray after a operation in Python

PythonServer Side ProgrammingProgramming

Suppose, we are given an array containing integer numbers. We can perform an operation where we can replace the value of array[i] with its squared value; or array[i] * array[i]. Only one operation of this kind is permitted and we have to return the sum of the maximum possible subarray after the operation. The subarray cannot be empty.

So, if the input is like array = [4, 1, -2, -1], then the output will be 17.

If we replace the value in array[0] with its squared value, the array becomes [16, 1, -2, -1]. The maximum subarray that is possible from this is [16, 1], and it has the maximum sum value 16 + 1 = 17.

To solve this, we will follow these steps −

  • dp1 := a new list containing the value negative infinity
  • dp2 := a new list containing the value negative infinity
  • for each num in array, do
    • insert maximum of ((last element of dp1 + num), num) at the end of dp1
    • insert maximum of ((second last element of dp1 + num^2), num^2, (last element of dp2 + num)) at the end of dp2
  • return the maximum element of dp2


Let us see the following implementation to get better understanding −

def solve(array):
   dp1 = [float('-inf')]
   dp2 = [float('-inf')]
   for num in array:
      dp1.append(max(dp1[-1] + num, num))
      dp2.append(max(dp1[-2] + num**2, num**2, dp2[-1]+num))
   return max(dp2)

print(solve([4, 1, -2, -1]))


[4, 1, -2, -1]


Published on 07-Oct-2021 11:44:21