Skip to main content

4. Kadane's Algorithm : Maximum Subarray Sum in an Array

Source: Kadane's Algorithm : Maximum Subarray Sum in an Array

Problem Statement

Example 1:
Input: nums = [2, 3, 5, -2, 7, -4]
Output: 15
Explanation: The subarray from index 0 to index 4 has the largest sum = 15, which is the maximum sum of any contiguous subarray.

Example 2:
Input: nums = [-2, -3, -7, -2, -10, -4]
Output: -2
Explanation: The largest sum is -2, which comes from taking the element at index 0 or index 3 as the subarray. Since all numbers are negative, the subarray with the least negative number gives the largest sum.

Disclaimer: Here is the practice link to help you assess your knowledge better. It's highly recommend trying to solve it before looking at the solution.

Approach 1: Better Approach

  • Iterate through the array with variable i, which represents the starting index of each subarray. The possible values for i range from 0 to n-1, where n is the size of the array.

    • Inside the first loop, run another loop with variable j that represents the ending index of the subarray. For each i, j can range from i to n-1.

    • For each subarray defined by i and j, iterate through its elements to calculate the sum. Maintain a variable, max, to store the maximum sum encountered so far during the iteration.

    • At each step, compare the current subarray sum with the current max value. If the current sum is greater, update the max value with the new sum.

    • Finally, after completing all iterations, return the max variable, which holds the maximum sum of any subarray.

  • Complexity: Time Complexity: O(N^3), where N is the size of the array. This is because we have three nested loops: one for the starting index, one for the ending index, and one for calculating the sum of the subarray.

    Space Complexity: O(1), as we are using a constant amount of space for variables, regardless of the input size.

Solutions

#include<bits/stdc++.h>
using namespace std;

class Solution {
public:
//Function to find maximum sum of subarrays
int maxSubArray(vector<int>& nums) {

/* Initialize maximum sum with
the smallest possible integer*/
int maxi = INT_MIN;

// Iterate over each starting index of subarrays
for (int i = 0; i < nums.size(); i++) {

/* Iterate over each ending index
of subarrays starting from i*/
for (int j = i; j < nums.size(); j++) {

// Variable to store the sum of the current subarray
int sum = 0;

// Calculate the sum of subarray nums[i...j]
for (int k = i; k <= j; k++) {
sum += nums[k];
}

/* Update maxi with the maximum of its current
value and the sum of the current subarray*/
maxi = max(maxi, sum);

}
}

// Return the maximum subarray sum found
return maxi;
}
};

int main() {
vector<int> arr = { -2, 1, -3, 4, -1, 2, 1, -5, 4};

//create an instance of Solution class
Solution sol;

int maxSum = sol.maxSubArray(arr);

//Print the max subarray sum
cout << "The maximum subarray sum is: " << maxSum << endl;
return 0;
}

Approach 2: Optimal Approach

  • Iterate through the array using a variable i. During each iteration, add the current element arr[i] to a running sum variable.

    • Keep track of the maximum sum encountered during the iteration by comparing the current sum with the previous maximum sum, and update it if the current sum is greater.

    • If at any point the sum becomes negative, reset it to 0, as a negative sum won't contribute positively to the overall maximum sum.

    • Continue the iteration until all elements in the array are processed.

    • Finally, return the maximum sum encountered during the iteration.

  • Complexity: Time Complexity: O(n), where n is the number of elements in the array. We traverse the array only once.

    Space Complexity: O(1). We use a constant amount of space for variables.

Solutions

#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
// Function to find maximum sum of subarrays
int maxSubArray(vector<int>& nums) {

// maximum sum
long long maxi = LLONG_MIN;

// current sum of subarray
long long sum = 0;

// Iterate through the array
for (int i = 0; i < nums.size(); i++) {

// Add current element to the sum
sum += nums[i];

// Update maxi if current sum is greater
if (sum > maxi) {
maxi = sum;
}

// Reset sum to 0 if it becomes negative
if (sum < 0) {
sum = 0;
}
}

// Return the maximum subarray sum found
return maxi;
}
};

int main() {
vector<int> arr = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };

// Create an instance of Solution class
Solution sol;

int maxSum = sol.maxSubArray(arr);

// Print the max subarray sum
cout << "The maximum subarray sum is: " << maxSum << endl;

return 0;
}

Reference