Maximum Subarray

Solution For Maximum Subarray

The Maximum Subarray problem is a classic problem in computer science that is often asked in programming interviews. In this problem, we are given an array of integers, and we have to find the contiguous subarray that has the largest sum.

For example, if we are given the array [−2,1,−3,4,−1,2,1,−5,4], then the contiguous subarray with the largest sum is [4,−1,2,1], and its sum is 6.

To solve this problem, we can use the Kadane’s algorithm. The algorithm is based on the observation that a subarray with the largest sum must end at one of the array elements. Therefore, we can iteratively calculate the maximum sum of all subarrays ending at each element of the array, and return the maximum of these sums.

Here is the step-by-step algorithm to solve the Maximum Subarray problem for the given array:

  1. Initialize two variables max_so_far and max_ending_here to 0.
  2. Iterate through the array from start to end.
  3. For each element in the array, add it to max_ending_here.
  4. If max_ending_here becomes negative, set it to 0.
  5. If max_ending_here is greater than max_so_far, set max_so_far to max_ending_here.
  6. Return max_so_far as the result.

Let’s implement this algorithm in Python:

def maxSubArray(nums):
max_so_far = 0
max_ending_here = 0
for num in nums:
max_ending_here += num
if max_ending_here < 0:
max_ending_here = 0
elif max_ending_here > max_so_far:
max_so_far = max_ending_here
return max_so_far

We can test this function with the example array:



The function correctly returns the maximum sum of the contiguous subarray.

This algorithm has a time complexity of O(n), where n is the length of the array. This is because we iterate through the array only once. Therefore, this algorithm is very efficient and can be used to solve the Maximum Subarray problem for very large arrays.

Step by Step Implementation For Maximum Subarray

class Solution {
    public int maxSubArray(int[] nums) {
        int maxSum = Integer.MIN_VALUE;
        int currentSum = 0;
        for(int i = 0; i < nums.length; i++) {
            currentSum += nums[i];
            if(currentSum > maxSum) {
                maxSum = currentSum;
            if(currentSum < 0) {
                currentSum = 0;
        return maxSum;
class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        max_sum = nums[0]
        current_sum = nums[0]
        for i in range(1, len(nums)):
            current_sum = max(nums[i], current_sum + nums[i])
            max_sum = max(current_sum, max_sum)
        return max_sum
 * @param {number[]} nums
 * @return {number}
 // Kadane's Algorithm
var maxSubArray = function(nums) {
    let localMax = nums[0];
    let globalMax = nums[0];
    for(let i = 1; i < nums.length; i++) {
        localMax = Math.max(nums[i], localMax + nums[i]);
        if(localMax > globalMax) {
            globalMax = localMax;
    return globalMax;
class Solution {
    int maxSubArray(vector& nums) {
        int max_so_far = nums[0]; 
        int curr_max = nums[0]; 
        for (int i = 1; i < nums.size(); i++) 
            curr_max = max(nums[i], curr_max + nums[i]); 
            max_so_far = max(max_so_far, curr_max); 
        return max_so_far; 
public int MaxSubArray(int[] nums) {
        // Kadane's algorithm
        int maxSoFar = nums[0];
        int maxEndingHere = nums[0];
        for (int i = 1; i < nums.Length; i++)
            maxEndingHere = Math.Max(maxEndingHere + nums[i], nums[i]);
            maxSoFar = Math.Max(maxSoFar, maxEndingHere);
        return maxSoFar;

Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]