AlgoMaster Logo

Maximum Subarray

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

The brute force approach involves checking every possible subarray and computing the sum of each one. This method is straightforward but inefficient for larger arrays due to its high time complexity.

Intuition:

  1. Iterate through each element of the array, treating it as the start of a subarray.
  2. For each start point, explore all possible end points and compute the sum for each subarray.
  3. Track the maximum sum encountered.

Code:

2. Kadane's Algorithm

Kadane's Algorithm provides an efficient way of finding the maximum subarray sum in linear time.

Intuition:

  1. Traverse the array, maintaining a running maximum sum of contiguous elements (currentSum).
  2. If currentSum drops below zero, reset it to the current element, as a negative currentSum would decrease the sum of any subarray including it.
  3. Track a global maximum (maxSum) across all encountered currentSum values.

Code: