- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

## Example

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]))

## Input

[4, 1, -2, -1]

## Output

17

- Related Questions & Answers
- Program to find the maximum sum of the subarray modulo by m in Python
- Program to find maximum ascending subarray sum using Python
- Program to find maximum absolute sum of any subarray in Python
- Program to find out the greatest subarray of a given length in python
- C++ program to find out the maximum sum of a minimally connected graph
- C++ Program to Find the maximum subarray sum using Binary Search approach
- Program to find maximum score of a good subarray in Python
- Program to Find Out the Maximum Final Power of a List in Python
- Program to find out the position of a ball after n reversals in Python
- Python Program to find out the price of a product after a number of days
- Program to find maximum product of contiguous subarray in Python
- Python Program to find out the sum of values in hyperrectangle cells
- Program to find the maximum sum of circular sublist in Python
- Program to find out the sum of the number of divisor of the divisors in Python
- Program to find maximum subarray min-product in Python

Advertisements