Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximize sum of an Array by flipping sign of all elements of a single subarray
Next article icon

Maximize subarray sum by inverting sign of elements of any subarray at most twice

Last Updated : 18 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array A of size n, find the maximum subarray sum after applying the given operation at most two times. In one operation, choose any two indices i and j and invert sign of all the elements from index i to index j, i.e, all positive elements in the range i to j become negative and all negative elements become positive.

Examples:

Input: A[] = {1, -2, -4, 3, 5, -6}
Output: 21
Explanation:
Inverting the array from index 1 to index 2 & from index 5 to index 5 (0-based indexing) to get {1, 2, 4, 3, 5, 6} with maximum subarray sum = 21

Input: A[] = {2, -1, -18, 3, -1, -39, 5, -2}
Output: 69

 

Approach: The idea is to first of all, merge all elements into groups. i.e all consecutive positive elements will be summed to one integer and will be placed in a new array arr and similarly for consecutive negative elements. After that, the problem reduces to find the maximum subarray sum after inverting at most two elements from this array.

The idea is to use Dynamic Programming. Now, create a dp[n][3] array and Here at every index in that dp array, maintain three numbers:

  • The first number represents the maximum subarray sum after inverting the no element in the array. So, dp[i][0] will simply run the logic of kadane’s algorithm for the maximum subarray sum.
  • The second number represents the maximum subarray sum after inverting exactly one element in the array. So, dp[i][1] will be the maximum of two values i.e dp[i-1][1] + arr[i] (maximum subarray sum after inverting one element till i and then adding the current element to it) and dp[i][0]+ (-arr[i]) ( i.e the previous non-inverted maximum subarray sum till i-1 and then adding current element after inverting ).
  • The third number represents the maximum subarray sum after inverting exactly two elements in the array. So, dp[i][2] will be maximum of two values i.e              (maximum subarray sum after inverting one element till i-1 and then adding the current element after inverting) and              (maximum subarray sum after inverting two elements till i-1 and adding the current element to it).
  • Keep a maxSum variable which will be updated after every index and will be equal to the maximum of the previous value of maxSum and all three current values i.e. dp[i][0], dp[i][1] and dp[i][2].
  • Return maxSum, which is the answer.

Below is the implementation of the above approach:
 

C++

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to merge alternate elements into groups
// of positive and negative
void mergeElements(int n, vector<int>& arr, int* A)
{
    int i = 0;
    int sum = 0;
    while (i < n) {
        sum = 0;
        while (i < n && A[i] >= 0) {
            sum += A[i];
            i++;
        }
        if (sum > 0) {
            arr.push_back(sum);
        }
        sum = 0;
        while (i < n && A[i] < 0) {
            sum += A[i];
            i++;
        }
        if (sum < 0) {
            arr.push_back(sum);
        }
    }
}
 
// Function to return the maximum
// after inverting at most 2 elements
int findMaxSum(vector<int>& arr, int n)
{
    int maxSum = 0;
    vector<vector<int> > dp(
n,
 vector<int>(3, INT_MIN));
 
    dp[0][0] = max(0, arr[0]);
    dp[0][1] = -1 * arr[0];
    for (int i = 1; i < n; ++i) {
 
        // dp[i][0] represents sum till ith index
        // without inverting any element.
        dp[i][0] = max(arr[i],
dp[i - 1][0] + arr[i]);
 
        // dp[i][1] represents sum till ith index
        // after inverting one element.
        dp[i][1] = max(0, dp[i - 1][0]) - arr[i];
        if (i >= 1) {
            dp[i][1] = max(dp[i][1],
dp[i - 1][1] + arr[i]);
 
            // dp[i][2] represents sum till ith index
            // after inverting two elements.
            dp[i][2] = dp[i - 1][1] - arr[i];
        }
 
        if (i >= 2) {
            dp[i][2] = max(dp[i][2],
dp[i - 1][2] + arr[i]);
        }
        maxSum = max(maxSum, dp[i][0]);
        maxSum = max(maxSum, dp[i][1]);
        maxSum = max(maxSum, dp[i][2]);
    }
    return maxSum;
}
 
// Driver Code
int main()
{
    int n = 8;
    int A[8] = { 2, -1, -18, 3, -1, -39, 5, -2 };
 
    // vector 'arr' contains sum of consecutive
    // positive or negative elements.
    vector<int> arr;
    mergeElements(n, arr, A);
 
    cout << findMaxSum(arr, arr.size());
    return 0;
}
                      
                       

Java

// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to merge alternate elements into groups
// of positive and negative
static Vector<Integer> mergeElements(int n, Vector<Integer> arr, int[] A)
{
    int i = 0;
    int sum = 0;
    while (i < n) {
        sum = 0;
        while (i < n && A[i] >= 0) {
            sum += A[i];
            i++;
        }
        if (sum > 0) {
            arr.add(sum);
        }
        sum = 0;
        while (i < n && A[i] < 0) {
            sum += A[i];
            i++;
        }
        if (sum < 0) {
            arr.add(sum);
        }
    }
    return arr;
}
 
// Function to return the maximum
// after inverting at most 2 elements
static int findMaxSum(Vector<Integer> arr, int n)
{
    int maxSum = 0;
    int [][]dp = new int[n][3];
 
 
    dp[0][0] = Math.max(0, arr.get(0));
    dp[0][1] = -1 * arr.get(0);
    for (int i = 1; i < n; ++i) {
 
        // dp[i][0] represents sum till ith index
        // without inverting any element.
        dp[i][0] = Math.max(arr.get(i),
dp[i - 1][0] + arr.get(i));
 
        // dp[i][1] represents sum till ith index
        // after inverting one element.
        dp[i][1] = Math.max(0, dp[i - 1][0]) - arr.get(i);
        if (i >= 1) {
            dp[i][1] = Math.max(dp[i][1],
dp[i - 1][1] + arr.get(i));
 
            // dp[i][2] represents sum till ith index
            // after inverting two elements.
            dp[i][2] = dp[i - 1][1] - arr.get(i);
        }
 
        if (i >= 2) {
            dp[i][2] = Math.max(dp[i][2],
dp[i - 1][2] + arr.get(i));
        }
        maxSum = Math.max(maxSum, dp[i][0]);
        maxSum = Math.max(maxSum, dp[i][1]);
        maxSum = Math.max(maxSum, dp[i][2]);
    }
    return maxSum;
}
 
// Driver Code
public static void main(String[] args)
{
    int n = 8;
    int A[] = { 2, -1, -18, 3, -1, -39, 5, -2 };
 
    // vector 'arr' contains sum of consecutive
    // positive or negative elements.
    Vector<Integer> arr = new Vector<Integer>();
   arr = mergeElements(n, arr, A);
 
    System.out.print(findMaxSum(arr, arr.size()));
}
}
 
// This code is contributed by 29AjayKumar
                      
                       

Python3

# python program for the above approach
 
INT_MIN = -2147483648
# Function to merge alternate elements into groups
# of positive and negative
 
 
def mergeElements(n, arr, A):
 
    i = 0
    sum = 0
    while (i < n):
        sum = 0
        while (i < n and A[i] >= 0):
            sum += A[i]
            i += 1
 
        if (sum > 0):
            arr.append(sum)
 
        sum = 0
        while (i < n and A[i] < 0):
            sum += A[i]
            i += 1
 
        if (sum < 0):
            arr.append(sum)
 
 
# Function to return the maximum
# after inverting at most 2 elements
def findMaxSum(arr, n):
 
    maxSum = 0
    dp = [[INT_MIN for _ in range(3)] for _ in range(n)]
 
    dp[0][0] = max(0, arr[0])
    dp[0][1] = -1 * arr[0]
    for i in range(1, n):
 
        # dp[i][0] represents sum till ith index
        # without inverting any element.
        dp[i][0] = max(arr[i], dp[i - 1][0] + arr[i])
 
        # dp[i][1] represents sum till ith index
        # after inverting one element.
        dp[i][1] = max(0, dp[i - 1][0]) - arr[i]
        if (i >= 1):
            dp[i][1] = max(dp[i][1], dp[i - 1][1] + arr[i])
 
            # dp[i][2] represents sum till ith index
            # after inverting two elements.
            dp[i][2] = dp[i - 1][1] - arr[i]
 
        if (i >= 2):
            dp[i][2] = max(dp[i][2], dp[i - 1][2] + arr[i])
 
        maxSum = max(maxSum, dp[i][0])
        maxSum = max(maxSum, dp[i][1])
        maxSum = max(maxSum, dp[i][2])
 
    return maxSum
 
 
# Driver Code
if __name__ == "__main__":
 
    n = 8
    A = [2, -1, -18, 3, -1, -39, 5, -2]
 
    # vector 'arr' contains sum of consecutive
    # positive or negative elements.
    arr = []
    mergeElements(n, arr, A)
    print(findMaxSum(arr, len(arr)))
 
    # This code is contributed by rakeshsahni
                      
                       

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
   
    // Function to merge alternate elements into groups
    // of positive and negative
    static void mergeElements(int n, List<int> arr, int[] A)
    {
        int i = 0;
        int sum = 0;
        while (i < n) {
            sum = 0;
            while (i < n && A[i] >= 0) {
                sum += A[i];
                i++;
            }
            if (sum > 0) {
                arr.Add(sum);
            }
            sum = 0;
            while (i < n && A[i] < 0) {
                sum += A[i];
                i++;
            }
            if (sum < 0) {
                arr.Add(sum);
            }
        }
    }
 
    // Function to return the maximum
    // after inverting at most 2 elements
    static int findMaxSum(List<int> arr, int n)
    {
        int maxSum = 0;
        int[, ] dp = new int[n, 3];
        for (int i = 0; i < n; i++)
            for (int j = 0; j < 3; j++)
                dp[i, j] = Int32.MinValue;
 
        dp[0, 0] = Math.Max(0, arr[0]);
        dp[0, 1] = -1 * arr[0];
        for (int i = 1; i < n; ++i) {
 
            // dp[i][0] represents sum till ith index
            // without inverting any element.
            dp[i, 0]
                = Math.Max(arr[i], dp[i - 1, 0] + arr[i]);
 
            // dp[i][1] represents sum till ith index
            // after inverting one element.
            dp[i, 1] = Math.Max(0, dp[i - 1, 0]) - arr[i];
            if (i >= 1) {
                dp[i, 1] = Math.Max(dp[i, 1],
                                    dp[i - 1, 1] + arr[i]);
 
                // dp[i][2] represents sum till ith index
                // after inverting two elements.
                dp[i, 2] = dp[i - 1, 1] - arr[i];
            }
 
            if (i >= 2) {
                dp[i, 2] = Math.Max(dp[i, 2],
                                    dp[i - 1, 2] + arr[i]);
            }
            maxSum = Math.Max(maxSum, dp[i, 0]);
            maxSum = Math.Max(maxSum, dp[i, 1]);
            maxSum = Math.Max(maxSum, dp[i, 2]);
        }
        return maxSum;
    }
 
    // Driver Code
    public static void Main()
    {
        int n = 8;
        int[] A = { 2, -1, -18, 3, -1, -39, 5, -2 };
 
        // vector 'arr' contains sum of consecutive
        // positive or negative elements.
        List<int> arr = new List<int>();
        mergeElements(n, arr, A);
 
        Console.WriteLine(findMaxSum(arr, arr.Count));
    }
}
 
// This code is contributed by ukasp.
                      
                       

Javascript

<script>
        // JavaScript Program to implement
        // the above approach
 
 
        // Function to merge alternate elements into groups
        // of positive and negative
        function mergeElements(n, arr, A) {
            let i = 0;
            let sum = 0;
            while (i < n) {
                sum = 0;
                while (i < n && A[i] >= 0) {
                    sum += A[i];
                    i++;
                }
                if (sum > 0) {
                    arr.push(sum);
                }
                sum = 0;
                while (i < n && A[i] < 0) {
                    sum += A[i];
                    i++;
                }
                if (sum < 0) {
                    arr.push(sum);
                }
            }
        }
 
        // Function to return the maximum
        // after inverting at most 2 elements
        function findMaxSum(arr, n) {
            let maxSum = 0;
 
            let dp = new Array(n);
 
            for (let i = 0; i < dp.length; i++) {
                dp[i] = new Array(3).fill(Number.MIN_VALUE);
            }
 
            dp[0][0] = Math.max(0, arr[0]);
            dp[0][1] = -1 * arr[0];
            for (let i = 1; i < n; ++i) {
 
                // dp[i][0] represents sum till ith index
                // without inverting any element.
                dp[i][0] = Math.max(arr[i],
                    dp[i - 1][0] + arr[i]);
 
                // dp[i][1] represents sum till ith index
                // after inverting one element.
                dp[i][1] = Math.max(0, dp[i - 1][0]) - arr[i];
                if (i >= 1) {
                    dp[i][1] = Math.max(dp[i][1],
                        dp[i - 1][1] + arr[i]);
 
                    // dp[i][2] represents sum till ith index
                    // after inverting two elements.
                    dp[i][2] = dp[i - 1][1] - arr[i];
                }
 
                if (i >= 2) {
                    dp[i][2] = Math.max(dp[i][2],
                        dp[i - 1][2] + arr[i]);
                }
                maxSum = Math.max(maxSum, dp[i][0]);
                maxSum = Math.max(maxSum, dp[i][1]);
                maxSum = Math.max(maxSum, dp[i][2]);
            }
            return maxSum;
        }
 
        // Driver Code
 
        let n = 8;
        let A = [2, -1, -18, 3, -1, -39, 5, -2];
 
        // vector 'arr' contains sum of consecutive
        // positive or negative elements.
        let arr = [];
        mergeElements(n, arr, A);
 
        document.write(findMaxSum(arr, arr.length));
 
// This code is contributed by Potta Lokesh
    </script>
                      
                       

 
 


Output
69


 

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


 



Next Article
Maximize sum of an Array by flipping sign of all elements of a single subarray

M

manupathria
Improve
Article Tags :
  • Arrays
  • DSA
  • Misc
  • subarray
  • subarray-sum
Practice Tags :
  • Arrays
  • Misc

Similar Reads

  • Maximum subarray sum by flipping signs of at most K array elements
    Given an array arr[] of N integers and an integer K, The task is to find the maximum sub-array sum by flipping signs of at most K array elements. Examples: Input: arr[] = {-6, 2, -1, -1000, 2}, k = 2 Output: 1009 We can flip the signs of -6 and -1000, to get maximum subarray sum as 1009 Input: arr[]
    9 min read
  • Maximize sum of an Array by flipping sign of all elements of a single subarray
    Given an array arr[] of N integers, the task is to find the maximum sum of the array that can be obtained by flipping signs of any subarray of the given array at most once. Examples: Input: arr[] = {-2, 3, -1, -4, -2} Output: 8Explanation: Flipping the signs of subarray {-1, -4, -2} modifies the arr
    9 min read
  • Maximum Subarray Sum after inverting at most two elements
    Given an array arr[] of integer elements, the task is to find maximum possible sub-array sum after changing the signs of at most two elements.Examples: Input: arr[] = {-5, 3, 2, 7, -8, 3, 7, -9, 10, 12, -6} Output: 61 We can get 61 from index 0 to 10 by changing the sign of elements at 4th and 7th i
    11 min read
  • Maximize the sum of maximum elements of at least K-sized subarrays
    Given an integer array arr[] of length N and an integer K, partition the array in some non-overlapping subarrays such that each subarray has size at least K and each element of the array should be part of a subarray. The task is to maximize the sum of maximum elements across all the subarrays. Examp
    7 min read
  • First subarray having sum at least half the maximum sum of any subarray of size K
    Given an array arr[] and an integer K, the task is to find the first subarray which has a sum greater than or equal to half of the maximum possible sum from any subarray of size K. Examples: Input: arr[] = {2, 4, 5, 1, 4, 6, 6, 2, 1, 0}, K = 3 Output: 6 2 1 Explanation: The given array has a maximum
    9 min read
  • Maximize length of Non-Decreasing Subsequence by reversing at most one Subarray
    Given a binary array arr[], the task is to find the maximum possible length of non-decreasing subsequence that can be generated by reversing a subarray at most once. Examples: Input: arr[] = {0, 1, 0, 1} Output: 4 Explanation: After reversing the subarray from index [2, 3], the array modifies to {0,
    9 min read
  • Reverse a subarray to maximize sum of even-indexed elements of given array
    Given an array arr[], the task is to maximize the sum of even-indexed elements by reversing a subarray and print the maximum sum obtained. Examples: Input: arr[] = {1, 2, 1, 2, 1} Output: 5 Explanation: Sum of initial even-indexed elements = a[0] + a[2] + a[4] = 1 + 1 + 1 = 3 Reversing subarray {1,
    9 min read
  • Reverse a subarray of the given array to minimize the sum of elements at even position
    Given an array arr[] of positive integers. The task is to reverse a subarray to minimize the sum of elements at even places and print the minimum sum. Note: Perform the move only one time. Subarray might not be reversed. Example: Input: arr[] = {1, 2, 3, 4, 5} Output: 7 Explanation: Sum of elements
    15 min read
  • Split array into K subarrays such that sum of maximum of all subarrays is maximized
    Given an array arr[] of size N and a number K, the task is to partition the given array into K contiguous subarrays such that the sum of the maximum of each subarray is the maximum possible. If it is possible to split the array in such a manner, then print the maximum possible sum. Otherwise, print
    11 min read
  • Maximum Subarray sum of A[] by adding any element of B[] at any end
    Given two arrays A[] and B[] having lengths N and M respectively, Where A[] and B[] can contain both positive and negative elements, the task is to find the maximum sub-array sum obtained by applying the below operations till the B[] has no element left in it: Choose either the leftmost or rightmost
    15 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences