Open In App

Maximum Subarray Sum possible by replacing an Array element by its Square

Last Updated : 14 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array a[] consisting of N integers, the task is to find the maximum subarray sum that can be obtained by replacing a single array element by its square.

Examples:

Input: a[] = {1, -5, 8, 12, -8} 
Output: 152 
Explanation: Replacing 12 by 144, the subarray {8, 144} generates the maximum possible subarray sum in the array.
Input: a[] = {-1, -2, -3} 
Output:
Explanation:

Naive Approach: The simplest approach to solve the problem is to replace every element with its square and for each of them, find the maximum subarray sum using Kadane's algorithm. Finally, print the maximum possible subarray sum obtained. 
Time Complexity: O(N2
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized using Dynamic Programming. Follow the steps below to solve the problem:

  • Initialize memoization table dp[][] where:
  • dp[i][0]: Stores the maximum subarray sum that can be obtained including ith element and without squaring any array element.
  • dp[i][1]: Stores the maximum subarray sum that can be including ith element and squaring one of the array elements
  • Therefore, the recurrence relations are:

dp[i][0] = max(dp[i-1][0] + a[i], a[i]), that is, either extend the previous subarray ending at i - 1th index or start a new subarray from ith index.
dp[i][1] = max(a[i]2, dp[i-1][0] + a[i]2, dp[i-1][1] + a[i]), that is, either start new subarray from ith index or extend previous subarray by adding a[i]2 to dp[i - 1][0] or add a[i] to dp[i - 1][1]
 

Below is the implementation of the above approach:

C++
Java Python3 C# JavaScript

Output
152

Time Complexity: O(N) 
Auxiliary Space: O(N)

Prefix-Suffix Sum approach :

  • Firstly, create a prefix sum array such that at i max prefix sum is stored.
  • Secondly, create a suffix sum array such that at i max suffix sum is stored.
  • After that simply iterate and check for each i few conditions -:

These two conditions should be checked firstly.

  • arr[0]*arr[0], 
  • arr[n-1]*arr[n-1]

Then check these 4 conditions for each i -:

  • prefix[i-1] + arr[i]*arr[i] + suffix[i+1], 
  • arr[i]*arr[i] + suffix[i+1], 
  • prefix[i-1] + arr[i]*arr[i], 
  • arr[i]*arr[i], 

Then max of all these will be the answer.

Below is the code to implement the same:

C++
Java Python3 JavaScript C#

Output
152

Time Complexity: O(N) 
Auxiliary Space: O(N)
 


Next Article

Similar Reads