304 North Cardinal St.
Dorchester Center, MA 02124

# Maximum Subarray LeetCode Solution

## Problem – Maximum Subarray LeetCode Solution

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

subarray is a contiguous part of an array.

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 = 
Output: 1
``````

Example 3:

``````Input: nums = [5,4,-1,7,8]
Output: 23
``````

Constraints:

• `1 <= nums.length <= 105`
• `-104 <= nums[i] <= 104`

### Maximum Subarray LeetCode Solution in Java

``````public static int maxSubArray(int[] A) {
int maxSoFar=A, maxEndingHere=A;
for (int i=1;i<A.length;++i){
maxEndingHere= Math.max(maxEndingHere+A[i],A[i]);
maxSoFar=Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
``````

### Maximum Subarray LeetCode Solution in Java

``````for i in range(1, len(nums)):
if nums[i-1] > 0:
nums[i] += nums[i-1]
return max(nums)
``````

### Maximum Subarray LeetCode Solution in C++

``````class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = size(nums), ans = INT_MIN;
for(int i = 0; i < n; i++)
for(int j = i, curSum = 0; j < n ; j++)
curSum += nums[j],
ans = max(ans, curSum);
return ans;
}
};
``````
##### Maximum Subarray LeetCode Solution Review:

In our experience, we suggest you solve this Maximum Subarray LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Maximum Subarray LeetCode Solution

Find on LeetCode

##### Conclusion:

I hope this Maximum Subarray LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions