Maximum subarray sum by flipping signs of at most K array elements in C++

In this problem, we are given an array and an integer k. Our task is to create a program that will find the maximum subarray sum by flipping signs of at most k array elements in C++.

Code description − Here, we will have to find at most k elements to flip in the array which will make the sum of subarray created from this array maximum.

Let’s take an example to understand the problem,

Input − array = {1, -2, 7, 0} k = 2

Output − 10

Explanation − we will flip only one element which is -2, it makes the array sum 10 which is the maximum possible.

To solve this problem, we will use the dynamic programming approach which will find the maximum possible sum of the array from ith index to jth index and store it in an array maxSumij[i][j] and consider both cases if element fliped or without element flip this will return the best-case, this will be done using a recursive call to the function. In the end, we will find the maximum element from the maxSumij[i][j] matrix.


Program to illustrate the working of our solution,

 Live Demo

#include <bits/stdc++.h>
using namespace std;
#define right 2
#define left 4
int arraySumij[left][right];
int findSubarraySum(int i, int flips, int n, int a[], int k){
   if (flips > k)
      return -1e9;
   if (i == n)
      return 0;
   if (arraySumij[i][flips] != -1)
      return arraySumij[i][flips];
   int maxSum = 0;
   maxSum = max(0, a[i] + findSubarraySum(i + 1, flips, n, a, k));
   maxSum = max(maxSum, -a[i] + findSubarraySum(i + 1, flips + 1, n, a, k));
   arraySumij[i][flips] = maxSum;
   return maxSum;
int maxSubarraySumFlip(int a[], int n, int k){
   memset(arraySumij, -1, sizeof(arraySumij));
   int maxSum = -100;
   for (int i = 0; i < n; i++)
      maxSum = max(maxSum, findSubarraySum(i, 0, n, a, k));
   return maxSum;
int main() {
   int a[] = {-3, 56, -1, 8};
   int n = sizeof(a) / sizeof(a[0]);
   int k = 2;
   cout<<"Maximum subarry sum by fipping signs of at most "<<k<<" element is "<<maxSubarraySumFlip(a, n, k);
   return 0;


Maximum subarry sum by fipping signs of at most 2 element is 66