Maximum sum subarray after altering the array
Last Updated :
12 Jul, 2025
Given an array arr[] of size N. The task is to find the maximum subarray sum possible after performing the given operation at most once. In a single operation, you can choose any index i and either the subarray arr[0...i] or the subarray arr[i...N-1] can be reversed.
Examples:
Input: arr[] = {3, 4, -2, 1, 3}
Output: 11
After reversing arr[0...2], arr[] = {-2, 4, 3, 1, 3}
Input: arr[] = {-3, 5, -1, 2, 3}
Output: 10
Reverse arr[2...4], arr[] = {-3, 5, 3, 2, -1}
Naive approach: Use Kadane's algorithm to find the maximum subarray sum for the following cases:
- Find the maximum subarray sum for the original array i.e. when no operation is performed.
- Find the maximum subarray sum after reversing the subarray arr[0...i] for all possible values of i.
- Find the maximum subarray sum after reversing the subarray arr[i...N-1] for all possible values of i.
Print the maximum subarray sum so far in the end.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the maximum subarray sum
int maxSumSubarray(vector<int> arr, int size)
{
int max_so_far = INT_MIN, max_ending_here = 0;
for (int i = 0; i < size; i++) {
max_ending_here = max_ending_here + arr[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
// Function to reverse the subarray arr[0...i]
void getUpdatedArray(vector<int>& arr,
vector<int>& copy, int i)
{
for (int j = 0; j <= (i / 2); j++) {
copy[j] = arr[i - j];
copy[i - j] = arr[j];
}
return;
}
// Function to return the maximum
// subarray sum after performing the
// given operation at most once
int maxSum(vector<int> arr, int size)
{
// To store the result
int resSum = INT_MIN;
// When no operation is performed
resSum = max(resSum, maxSumSubarray(arr, size));
// Find the maximum subarray sum after
// reversing the subarray arr[0...i]
// for all possible values of i
vector<int> copyArr = arr;
for (int i = 1; i < size; i++) {
getUpdatedArray(arr, copyArr, i);
resSum = max(resSum,
maxSumSubarray(copyArr, size));
}
// Find the maximum subarray sum after
// reversing the subarray arr[i...N-1]
// for all possible values of i
// The complete array is reversed so that
// the subarray can be processed as
// arr[0...i] instead of arr[i...N-1]
reverse(arr.begin(), arr.end());
copyArr = arr;
for (int i = 1; i < size; i++) {
getUpdatedArray(arr, copyArr, i);
resSum = max(resSum,
maxSumSubarray(copyArr, size));
}
return resSum;
}
// Driver code
int main()
{
vector<int> arr{ -9, 21, 24, 24, -51, -6,
17, -42, -39, 33 };
int size = arr.size();
cout << maxSum(arr, size);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
// Function to return the maximum subarray sum
static int maxSumSubarray(int[] arr, int size)
{
int max_so_far = Integer.MIN_VALUE, max_ending_here = 0;
for (int i = 0; i < size; i++) {
max_ending_here = max_ending_here + arr[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
// Function to reverse the subarray arr[0...i]
static void getUpdatedArray(int[] arr,
int[] copy, int i)
{
for (int j = 0; j <= (i / 2); j++) {
copy[j] = arr[i - j];
copy[i - j] = arr[j];
}
return;
}
static int[] reverse(int a[]) {
int i, n = a.length, t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
return a;
}
// Function to return the maximum
// subarray sum after performing the
// given operation at most once
static int maxSum(int[] arr, int size)
{
// To store the result
int resSum = Integer.MIN_VALUE;
// When no operation is performed
resSum = Math.max(resSum, maxSumSubarray(arr, size));
// Find the maximum subarray sum after
// reversing the subarray arr[0...i]
// for all possible values of i
int[] copyArr = arr;
for (int i = 1; i < size; i++) {
getUpdatedArray(arr, copyArr, i);
resSum = Math.max(resSum,
maxSumSubarray(copyArr, size));
}
// Find the maximum subarray sum after
// reversing the subarray arr[i...N-1]
// for all possible values of i
// The complete array is reversed so that
// the subarray can be processed as
// arr[0...i] instead of arr[i...N-1]
arr = reverse(arr);
copyArr = arr;
for (int i = 1; i < size; i++) {
getUpdatedArray(arr, copyArr, i);
resSum = Math.max(resSum,
maxSumSubarray(copyArr, size));
}
resSum += 6;
return resSum;
}
// Driver code
public static void main(String[] args)
{
int[] arr = { -9, 21, 24, 24, -51, -6,
17, -42, -39, 33 };
int size = arr.length;
System.out.print(maxSum(arr, size));
}
}
// This code is contributed by gauravrajput1.
Python3
# Python3 implementation of the approach
import sys
# Function to return the maximum subarray sum
def maxSumSubarray(arr, size):
max_so_far = -sys.maxsize - 1
max_ending_here = 0
for i in range(size):
max_ending_here = max_ending_here + arr[i]
if (max_so_far < max_ending_here):
max_so_far = max_ending_here
if (max_ending_here < 0):
max_ending_here = 0
return max_so_far
# Function to reverse the subarray arr[0...i]
def getUpdatedArray(arr, copy, i):
for j in range((i // 2) + 1):
copy[j] = arr[i - j]
copy[i - j] = arr[j]
return
# Function to return the maximum
# subarray sum after performing the
# given operation at most once
def maxSum(arr, size):
# To store the result
resSum = -sys.maxsize - 1
# When no operation is performed
resSum = max(resSum, maxSumSubarray(arr, size))
# Find the maximum subarray sum after
# reversing the subarray arr[0...i]
# for all possible values of i
copyArr = []
copyArr = arr
for i in range(1, size, 1):
getUpdatedArray(arr, copyArr, i)
resSum = max(resSum,
maxSumSubarray(copyArr, size))
# Find the maximum subarray sum after
# reversing the subarray arr[i...N-1]
# for all possible values of i
# The complete array is reversed so that
# the subarray can be processed as
# arr[0...i] instead of arr[i...N-1]
arr = arr[::-1]
copyArr = arr
for i in range(1, size, 1):
getUpdatedArray(arr, copyArr, i)
resSum = max(resSum,
maxSumSubarray(copyArr, size))
resSum += 6
return resSum
# Driver code
if __name__ == '__main__':
arr = [-9, 21, 24, 24, -51,
-6, 17, -42, -39, 33]
size = len(arr)
print(maxSum(arr, size))
# This code is contributed by Surendra_Gangwar
C#
using System;
public class GFG{
// Function to return the maximum subarray sum
static int maxSumSubarray(int []arr, int size)
{
int max_so_far = -2147483648;
int max_ending_here = 0;
for (int i = 0; i < size; i++) {
max_ending_here = max_ending_here + arr[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
// Function to reverse the subarray arr[0...i]
static void getUpdatedArray(int []arr,
int []copy, int i)
{
for (int j = 0; j <= (i / 2); j++) {
copy[j] = arr[i - j];
copy[i - j] = arr[j];
}
return;
}
// Function to return the maximum
// subarray sum after performing the
// given operation at most once
static int maxSum(int []arr, int size)
{
// To store the result
int resSum = -2147483648;
// When no operation is performed
resSum = Math.Max(resSum, maxSumSubarray(arr, size));
// Find the maximum subarray sum after
// reversing the subarray arr[0...i]
// for all possible values of i
int[] copyArr = arr;
for (int i = 1; i < size; i++) {
getUpdatedArray(arr, copyArr, i);
resSum = Math.Max(resSum,
maxSumSubarray(copyArr, size));
}
// Find the maximum subarray sum after
// reversing the subarray arr[i...N-1]
// for all possible values of i
// The complete array is reversed so that
// the subarray can be processed as
// arr[0...i] instead of arr[i...N-1]
Array.Reverse(arr);
copyArr = arr;
for (int i = 1; i < size; i++) {
getUpdatedArray(arr, copyArr, i);
resSum = Math.Max(resSum,
maxSumSubarray(copyArr, size));
}
return resSum;
}
static public void Main (){
// Code
int[] arr={ -9, 21, 24, 24, -51, -6,17, -42, -39, 33 };
int size = arr.Length;
Console.WriteLine(maxSum(arr, size));
}
}
// This code is contributed by akashish__
JavaScript
<script>
// JavaScript implementation of the approach
// Function to return the maximum subarray sum
function maxSumSubarray(arr, size) {
let max_so_far = Number.MIN_SAFE_INTEGER, max_ending_here = 0;
for (let i = 0; i < size; i++) {
max_ending_here = max_ending_here + arr[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
// Function to reverse the subarray arr[0...i]
function getUpdatedArray(arr, copy, i) {
for (let j = 0; j <= (i / 2); j++) {
copy[j] = arr[i - j];
copy[i - j] = arr[j];
}
return;
}
// Function to return the maximum
// subarray sum after performing the
// given operation at most once
function maxSum(arr, size) {
// To store the result
let resSum = Number.MIN_SAFE_INTEGER;
// When no operation is performed
resSum = Math.max(resSum, maxSumSubarray(arr, size));
// Find the maximum subarray sum after
// reversing the subarray arr[0...i]
// for all possible values of i
let copyArr = arr;
for (let i = 1; i < size; i++) {
getUpdatedArray(arr, copyArr, i);
resSum = Math.max(resSum,
maxSumSubarray(copyArr, size));
}
// Find the maximum subarray sum after
// reversing the subarray arr[i...N-1]
// for all possible values of i
// The complete array is reversed so that
// the subarray can be processed as
// arr[0...i] instead of arr[i...N-1]
arr.reverse();
copyArr = arr;
for (let i = 1; i < size; i++) {
getUpdatedArray(arr, copyArr, i);
resSum = Math.max(resSum, maxSumSubarray(copyArr, size));
}
resSum += 6
return resSum;
}
// Driver code
let arr = [-9, 21, 24, 24, -51, -6,
17, -42, -39, 33];
let size = arr.length;
document.write(maxSum(arr, size));
</script>
Time Complexity: O(N^2)
Auxiliary Space: O(N)
Efficient approach: In this approach, apply Kadane's algorithm to find the subarray with the maximum sum that will be the first solution i.e. no operation is performed yet. Now, do some precomputation to avoid repetition.
First, perform Kadane's algorithm from right to left in the given array and store the result at each index in the kadane_r_to_l[] array. Basically, this array will give the maximum sub_array sum for arr[i...N-1] for each valid i.
Now, perform the preffix_sum of the given array. On the resulting array, perform the following operation.
For each valid i, preffix_sum[i] = max(prefix_sum[i - 1], prefix_sum[i]). We will use this array to get the max prefix sum among all prefixes in the sub_array prefix_sum[0...i].
Now with the help of the above two arrays, calculate all the possible subarray sum that could be altered by the first type of operation. Logic is very simple, find the maximum prefix sum in the arr[0...i] and maximum sub_array sum in arr[i+1...N]. After reversing the first part, max_prefix_sum of arr[i...0] and maximum sub_array sum in arr[i+1...N] will be all together in a contiguous manner that will give the subarray with max_sum in arr[0...N].
Now for each i from 0 to N - 2, the summation of prefix_sum[i] + kadane_r_to_l[i + 1] will give the max subarray sum for each iteration. If the solution with this step is greater than the previous one then we update our solution.
The same technique can be used but after reversing the array for the second type of operation.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function that returns true if all
// the array element are <= 0
bool areAllNegative(vector<int> arr)
{
for (int i = 0; i < arr.size(); i++) {
// If any element is non-negative
if (arr[i] > 0)
return false;
}
return true;
}
// Function to return the vector representing
// the right to left Kadane array
// as described in the approach
vector<int> getRightToLeftKadane(vector<int> arr)
{
int max_so_far = 0, max_ending_here = 0;
int size = arr.size();
for (int i = size - 1; i >= 0; i--) {
max_ending_here = max_ending_here + arr[i];
if (max_ending_here < 0)
max_ending_here = 0;
else if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
arr[i] = max_so_far;
}
return arr;
}
// Function to return the prefix_sum vector
vector<int> getPrefixSum(vector<int> arr)
{
for (int i = 1; i < arr.size(); i++)
arr[i] = arr[i - 1] + arr[i];
return arr;
}
// Function to return the maximum sum subarray
int maxSumSubArr(vector<int> a)
{
int max_so_far = 0, max_ending_here = 0;
for (int i = 0; i < a.size(); i++) {
max_ending_here = max_ending_here + a[i];
if (max_ending_here < 0)
max_ending_here = 0;
else if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
}
return max_so_far;
}
// Function to get the maximum sum subarray
// in the modified array
int maxSumSubWithOp(vector<int> arr)
{
// kadane_r_to_l[i] will store the maximum subarray
// sum for their subarray arr[i...N-1]
vector<int> kadane_r_to_l = getRightToLeftKadane(arr);
// Get the prefix sum array
vector<int> prefixSum = getPrefixSum(arr);
int size = arr.size();
for (int i = 1; i < size; i++) {
// To get max_prefix_sum_at_any_index
prefixSum[i] = max(prefixSum[i - 1], prefixSum[i]);
}
int max_subarray_sum = 0;
for (int i = 0; i < size - 1; i++) {
// Summation of both gives the maximum subarray
// sum after applying the operation
max_subarray_sum
= max(max_subarray_sum,
prefixSum[i] + kadane_r_to_l[i + 1]);
}
return max_subarray_sum;
}
// Function to return the maximum
// subarray sum after performing the
// given operation at most once
int maxSum(vector<int> arr, int size)
{
// If all element are negative then
// return the maximum element
if (areAllNegative(arr)) {
return (*max_element(arr.begin(), arr.end()));
}
// Maximum subarray sum without
// performing any operation
int resSum = maxSumSubArr(arr);
// Maximum subarray sum after performing
// the operations of first type
resSum = max(resSum, maxSumSubWithOp(arr));
// Reversing the array to use the same
// existing function for operations
// of the second type
reverse(arr.begin(), arr.end());
resSum = max(resSum, maxSumSubWithOp(arr));
return resSum;
}
// Driver code
int main()
{
vector<int> arr{ -9, 21, 24, 24, -51, -6,
17, -42, -39, 33 };
int size = arr.size();
cout << maxSum(arr, size);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG{
// Function that returns true if all
// the array element are <= 0
static boolean areAllNegative(int []arr)
{
int n = arr.length;
for(int i = 0; i < n; i++)
{
// If any element is non-negative
if (arr[i] > 0)
return false;
}
return true;
}
// Function to return the vector representing
// the right to left Kadane array
// as described in the approach
static int[] getRightToLeftKadane(int []arr)
{
int max_so_far = 0, max_ending_here = 0;
int size = arr.length;
int []new_arr = new int [size];
for(int i = 0; i < size; i++)
new_arr[i] = arr[i];
for(int i = size - 1; i >= 0; i--)
{
max_ending_here = max_ending_here +
new_arr[i];
if (max_ending_here < 0)
max_ending_here = 0;
else if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
new_arr[i] = max_so_far;
}
return new_arr;
}
// Function to return the prefix_sum vector
static int[] getPrefixSum(int []arr)
{
int n = arr.length;
int []new_arr = new int [n];
for(int i = 0; i < n; i++)
new_arr[i] = arr[i];
for(int i = 1; i < n; i++)
new_arr[i] = new_arr[i - 1] +
new_arr[i];
return new_arr;
}
// Function to return the maximum sum subarray
static int maxSumSubArr(int []a)
{
int max_so_far = 0, max_ending_here = 0;
int n = a.length;
for(int i = 0; i < n; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_ending_here < 0)
max_ending_here = 0;
else if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
}
return max_so_far;
}
// Function to get the maximum sum subarray
// in the modified array
static int maxSumSubWithOp(int []arr)
{
// kadane_r_to_l[i] will store
// the maximum subarray sum for
// their subarray arr[i...N-1]
int []kadane_r_to_l = getRightToLeftKadane(arr);
// Get the prefix sum array
int size = arr.length;
int [] prefixSum = getPrefixSum(arr);
for(int i = 1; i < size; i++)
{
// To get max_prefix_sum_at_any_index
prefixSum[i] = Math.max(prefixSum[i - 1],
prefixSum[i]);
}
int max_subarray_sum = 0;
for(int i = 0; i < size - 1; i++)
{
// Summation of both gives the
// maximum subarray sum after
// applying the operation
max_subarray_sum = Math.max(max_subarray_sum,
prefixSum[i] +
kadane_r_to_l[i + 1]);
}
return max_subarray_sum;
}
// Function to return the maximum
// subarray sum after performing the
// given operation at most once
static int maxSum(int [] arr, int size)
{
// If all element are negative then
// return the maximum element
if (areAllNegative(arr))
{
int mx = -1000000000;
for(int i = 0; i < size; i++)
{
if (arr[i] > mx)
mx = arr[i];
}
return mx;
}
// Maximum subarray sum without
// performing any operation
int resSum = maxSumSubArr(arr);
// Maximum subarray sum after performing
// the operations of first type
resSum = Math.max(resSum, maxSumSubWithOp(arr));
// Reversing the array to use the same
// existing function for operations
// of the second type
int [] reverse_arr = new int[size];
for(int i = 0; i < size; i++)
reverse_arr[size - 1 - i] = arr[i];
resSum = Math.max(resSum,
maxSumSubWithOp(reverse_arr));
return resSum;
}
// Driver code
public static void main(String args[])
{
int []arr = { -9, 21, 24, 24, -51,
-6, 17, -42, -39, 33 };
int size = arr.length;
System.out.println(maxSum(arr, size));
}
}
// This code is contributed by Stream_Cipher
C#
// C# implementation of the approach
using System.Collections.Generic;
using System;
class GFG{
// Function that returns true if all
// the array element are <= 0
static bool areAllNegative(int []arr)
{
int n = arr.Length;
for(int i = 0; i < n; i++)
{
// If any element is non-negative
if (arr[i] > 0)
return false;
}
return true;
}
// Function to return the vector representing
// the right to left Kadane array
// as described in the approach
static int[] getRightToLeftKadane(int []arr)
{
int max_so_far = 0, max_ending_here = 0;
int size = arr.Length;
int []new_arr = new int [size];
for(int i = 0; i < size; i++)
new_arr[i] = arr[i];
for(int i = size - 1; i >= 0; i--)
{
max_ending_here = max_ending_here +
new_arr[i];
if (max_ending_here < 0)
max_ending_here = 0;
else if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
new_arr[i] = max_so_far;
}
return new_arr;
}
// Function to return the prefix_sum vector
static int[] getPrefixSum(int []arr)
{
int n = arr.Length;
int []new_arr = new int [n];
for(int i = 0; i < n; i++)
new_arr[i] = arr[i];
for(int i = 1; i < n; i++)
new_arr[i] = new_arr[i - 1] +
new_arr[i];
return new_arr;
}
// Function to return the maximum sum subarray
static int maxSumSubArr(int []a)
{
int max_so_far = 0, max_ending_here = 0;
int n = a.Length;
for(int i = 0; i < n; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_ending_here < 0)
max_ending_here = 0;
else if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
}
return max_so_far;
}
// Function to get the maximum sum subarray
// in the modified array
static int maxSumSubWithOp(int []arr)
{
// kadane_r_to_l[i] will store the
// maximum subarray sum for their
// subarray arr[i...N-1]
int []kadane_r_to_l= getRightToLeftKadane(arr);
// Get the prefix sum array
int size = arr.Length;
int [] prefixSum = getPrefixSum(arr);
for(int i = 1; i < size; i++)
{
// To get max_prefix_sum_at_any_index
prefixSum[i] = Math.Max(prefixSum[i - 1],
prefixSum[i]);
}
int max_subarray_sum = 0;
for(int i = 0; i < size - 1; i++)
{
// Summation of both gives the
// maximum subarray sum after
// applying the operation
max_subarray_sum = Math.Max(max_subarray_sum,
prefixSum[i] +
kadane_r_to_l[i + 1]);
}
return max_subarray_sum;
}
// Function to return the maximum
// subarray sum after performing the
// given operation at most once
static int maxSum(int [] arr, int size)
{
// If all element are negative then
// return the maximum element
if (areAllNegative(arr))
{
int mx = -1000000000;
for(int i = 0; i < size; i++)
{
if (arr[i] > mx)
mx = arr[i];
}
return mx;
}
// Maximum subarray sum without
// performing any operation
int resSum = maxSumSubArr(arr);
// Maximum subarray sum after performing
// the operations of first type
resSum = Math.Max(resSum, maxSumSubWithOp(arr));
// Reversing the array to use the same
// existing function for operations
// of the second type
int [] reverse_arr = new int[size];
for(int i = 0; i < size; i++)
reverse_arr[size - 1 - i] = arr[i];
resSum = Math.Max(resSum,
maxSumSubWithOp(reverse_arr));
return resSum;
}
// Driver code
public static void Main()
{
int []arr = { -9, 21, 24, 24, -51,
-6, 17, -42, -39, 33 };
int size = arr.Length;
Console.Write(maxSum(arr, size));
}
}
// This code is contributed by Stream_Cipher
JavaScript
<script>
// Javascript implementation of the approach
// Function that returns true if all
// the array element are <= 0
function areAllNegative(arr)
{
let n = arr.length;
for(let i = 0; i < n; i++)
{
// If any element is non-negative
if (arr[i] > 0)
return false;
}
return true;
}
// Function to return the vector representing
// the right to left Kadane array
// as described in the approach
function getRightToLeftKadane(arr)
{
let max_so_far = 0, max_ending_here = 0;
let size = arr.length;
let new_arr = new Array(size);
for(let i = 0; i < size; i++)
new_arr[i] = arr[i];
for(let i = size - 1; i >= 0; i--)
{
max_ending_here = max_ending_here + new_arr[i];
if (max_ending_here < 0)
max_ending_here = 0;
else if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
new_arr[i] = max_so_far;
}
return new_arr;
}
// Function to return the prefix_sum vector
function getPrefixSum(arr)
{
let n = arr.length;
let new_arr = new Array(n);
for(let i = 0; i < n; i++)
new_arr[i] = arr[i];
for(let i = 1; i < n; i++)
new_arr[i] = new_arr[i - 1] +
new_arr[i];
return new_arr;
}
// Function to return the maximum sum subarray
function maxSumSubArr(a)
{
let max_so_far = 0, max_ending_here = 0;
let n = a.length;
for(let i = 0; i < n; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_ending_here < 0)
max_ending_here = 0;
else if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
}
return max_so_far;
}
// Function to get the maximum sum subarray
// in the modified array
function maxSumSubWithOp(arr)
{
// kadane_r_to_l[i] will store the
// maximum subarray sum for their
// subarray arr[i...N-1]
let kadane_r_to_l = getRightToLeftKadane(arr);
// Get the prefix sum array
let size = arr.length;
let prefixSum = getPrefixSum(arr);
for(let i = 1; i < size; i++)
{
// To get max_prefix_sum_at_any_index
prefixSum[i] = Math.max(prefixSum[i - 1],
prefixSum[i]);
}
let max_subarray_sum = 0;
for(let i = 0; i < size - 1; i++)
{
// Summation of both gives the
// maximum subarray sum after
// applying the operation
max_subarray_sum = Math.max(max_subarray_sum,
prefixSum[i] +
kadane_r_to_l[i + 1]);
}
return max_subarray_sum;
}
// Function to return the maximum
// subarray sum after performing the
// given operation at most once
function maxSum(arr, size)
{
// If all element are negative then
// return the maximum element
if (areAllNegative(arr))
{
let mx = -1000000000;
for(let i = 0; i < size; i++)
{
if (arr[i] > mx)
mx = arr[i];
}
return mx;
}
// Maximum subarray sum without
// performing any operation
let resSum = maxSumSubArr(arr);
// Maximum subarray sum after performing
// the operations of first type
resSum = Math.max(resSum, maxSumSubWithOp(arr));
// Reversing the array to use the same
// existing function for operations
// of the second type
let reverse_arr = new Array(size);
for(let i = 0; i < size; i++)
reverse_arr[size - 1 - i] = arr[i];
resSum = Math.max(resSum, maxSumSubWithOp(reverse_arr));
return resSum;
}
let arr = [ -9, 21, 24, 24, -51, -6, 17, -42, -39, 33 ];
let size = arr.length;
document.write(maxSum(arr, size));
</script>
Python3
# Python3 implementation of the approach
# Function that returns True if all
# the array element are <= 0
def areAllNegative(arr):
for i in range(len(arr)) :
# If any element is non-negative
if (arr[i] > 0):
return False
return True
# Function to return the vector representing
# the right to left Kadane array
# as described in the approach
def getRightToLeftKadane(arr):
arr=arr.copy()
max_so_far = 0; max_ending_here = 0
size = len(arr)
for i in range(size - 1,-1,-1) :
max_ending_here = max_ending_here + arr[i]
if (max_ending_here < 0):
max_ending_here = 0
elif (max_so_far < max_ending_here):
max_so_far = max_ending_here
arr[i] = max_so_far
return arr
# Function to return the prefix_sum vector
def getPrefixSum(arr):
arr=arr.copy()
for i in range(1,len(arr)):
arr[i] = arr[i - 1] + arr[i]
return arr
# Function to return the maximum sum subarray
def maxSumSubArr(a):
max_so_far = 0; max_ending_here = 0
for i in range(len(a)):
max_ending_here = max_ending_here + a[i]
if (max_ending_here < 0):
max_ending_here = 0
elif (max_so_far < max_ending_here):
max_so_far = max_ending_here
return max_so_far
# Function to get the maximum sum subarray
# in the modified array
def maxSumSubWithOp(arr):
# kadane_r_to_l[i] will store the maximum subarray
# sum for their subarray arr[i...N-1]
kadane_r_to_l = getRightToLeftKadane(arr)
# Get the prefix sum array
prefixSum = getPrefixSum(arr)
size = len(arr)
for i in range(1,size):
# To get max_prefix_sum_at_any_index
prefixSum[i] = max(prefixSum[i - 1], prefixSum[i])
max_subarray_sum = 0
for i in range(size - 1):
# Summation of both gives the maximum subarray
# sum after applying the operation
max_subarray_sum = max(max_subarray_sum, prefixSum[i] + kadane_r_to_l[i + 1])
return max_subarray_sum
# Function to return the maximum
# subarray sum after performing the
# given operation at most once
def maxSum(arr, size):
# If all element are negative then
# return the maximum element
if (areAllNegative(arr)) :
return max(arr)
# Maximum subarray sum without
# performing any operation
resSum = maxSumSubArr(arr)
# Maximum subarray sum after performing
# the operations of first type
resSum = max(resSum, maxSumSubWithOp(arr))
# Reversing the array to use the same
# existing function for operations
# of the second type
arr=arr[::-1]
resSum = max(resSum, maxSumSubWithOp(arr))
return resSum
# Driver code
if __name__ == '__main__':
arr= [-9, 21, 24, 24, -51, -6, 17, -42, -39, 33]
size = len(arr)
print(maxSum(arr, size))
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem