Maximum Subarray [Easy]

25 Aug 2026, Updated: 24 Sep 2026 2 min read
2
The Maximum Subarray problem requires finding the contiguous subarray with the largest possible sum.

Problem

Given an integer array nums, find the contiguous subarray with the largest sum and return that sum.

Example(s)

Consider the following example to understand the expected input and output.

Input

nums = [-2,1,-3,4,-1,2,1,-5,4]

Output

6

Explanation

Maximum subarray = [4,-1,2,1]
4 + (-1) + 2 + 1 = 6

Solution

This problem can be solved optimally using Kadane's Algorithm.

As we move through the array, we maintain the sum of the current subarray. For each element, we have two choices: extend the current subarray by adding the element, or start a new subarray from the current element.

If extending the current subarray produces a smaller sum than starting from the current element, we start a new subarray. This allows us to discard a previous subarray whose negative contribution would reduce any future sum.

We also maintain maxSum, which stores the largest subarray sum found so far.
public int maxSubArray(int[] nums) {
    int currentSum = nums[0];
    int maxSum = nums[0];

    for (int i = 1; i < nums.length; i++) {
        // Start new or extend the current subarray.
        currentSum = Math.max(nums[i], currentSum + nums[i]);

        // Update the maximum sum.
        maxSum = Math.max(maxSum, currentSum);
    }

    return maxSum;
}

Complexity

Each element is processed exactly once, resulting in O(n) time complexity. Only two variables are used, requiring O(1) extra space.
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion