Search

Maximum Subarray / Kadane's Algorithm

Updated: Mar 25, 2021

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.


Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Example 2:

Input: nums = [1]
Output: 1

Example 3:

Input: nums = [0]
Output: 0

Example 4:

Input: nums = [-1]
Output: -1

Example 5:

Input: nums = [-100000]
Output: -100000

Constraints:

  • 1 <= nums.length <= 3 * 104

  • -105 <= nums[i] <= 105

Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.


Solution:


Approach 1: Brute Force O(n^2)


class Solution {
public int maxSubArray(int[] nums) {
       int max=Integer.MIN_VALUE;
        for(int i=0; i<nums.length;i++)
        {
            int sum=0;
            for(int j=i;j<nums.length;j++)
            {
                sum+=nums[j];
                max=Math.max(max,sum);
            }
        }
        return max;
        
    }
}


Approach 2: Kadane's Algorithm O(n)


class Solution {
public int maxSubArray(int[] nums) {
        int sum=nums[0];
        int output=nums[0];
        for(int i=1; i<nums.length;i++)
        {
            sum=Math.max(nums[i],sum+nums[i]);
            output=Math.max(output,sum);
        }
        return output;
        
    }
}

40 views0 comments

Recent Posts

See All

A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The f

The numeric value of a lowercase character is defined as its position (1-indexed) in the alphabet, so the numeric value of a is 1, the numeric value of b is 2, the numeric value of c is 3, and so on.