Back to photostream

Maximum Subarray Leetcode Solution

Problem Statement

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

Example

nums =

6

Explanation:

 

has the largest sum = 6.

nums =

-1

Approach 1 (Divide and Conquer)

In this approach we will be discussing about divide and conquer technique to solve this problem. We are trying to find that contiguous subarray which has maximum sum. So we can say that the optimum subarray may lie in any part of the array. So we make three cases which will cover all possibilities:

 

Case 1:

Max subarray lies completely in the left half of the array.

Case 2:

Max subarray lies completely in the right half of the array.

Case 3:

Partial portion of max subarray lies in the left half and another partial portion of it lies in the second half (i.e. subarray is crossing the mid element of the array)

 

As we can see case 1 and case 2 is basically a subproblem of N/2 sized array having same definition as main problem. Where N is the size of the current array. So we can simply recurs the function over two halves of the array.

Now the main part is case 3 which we have to solve in the current function and then we can return the maximum sum out of these 3 cases.

 

Lets see how we can solve for case 3:

 

Suppose we have array =

We find mid index to divide it into two equal halves.

mid index = (0+9)/2 = 4

 

As case 3 is saying that max sum will cross the mid element.

 

www.tutorialcup.com/leetcode-solutions/maximum-subarray-l...

42 views
0 faves
0 comments
Uploaded on August 13, 2021
Taken on February 10, 2021