Maximum subarray sum in O(n) using prefix sum in C++

C++Server Side ProgrammingProgramming

Problem statement

Given an Array of Positive and Negative Integers, find out the Maximum Subarray Sum in that Array

Example

If input array is − {-12, -5, 4, -1, -7, 1, 8, -3} then output is 9

Algorithm

  • Calculate the prefix sum of the input array.

  • Initialize− min_prefix_sum = 0, res = -infinite

  • Maintain a loop for i = 0 to n. (n is the size of the input array).

    • cand = prefix_sum[i] – mini

    • If cand is greater than res (maximum subarray sum so far), then update res by cand.

    • If prefix_sum[i] is less than min_prefix_sum (minimum prefix sum so far), then update min_prefix_sum by prefix_sum[i].

  • Return res

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int maximumSumSubarray(int *arr, int n){
   int minPrefixSum = 0;
   int res = numeric_limits<int>::min();
   int prefixSum[n];
   prefixSum[0] = arr[0];
   for (int i = 1; i < n; i++) {
      prefixSum[i] = prefixSum[i - 1] + arr[i];
   }
   for (int i = 0; i < n; i++) {
      res = max(res, prefixSum[i] - minPrefixSum);
      minPrefixSum = min(minPrefixSum, prefixSum[i]);
   }
   return res;
}
int main(){
   int arr[] = {-12, -5, 4, -1, -7, 1, 8, -3};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Result = " << maximumSumSubarray(arr, n) <<endl;
   return 0;
}

Output

When you compile and execute above program. It generates following output −

Result = 9
raja
Published on 30-Jan-2020 16:34:15
Advertisements