# Dynamic Programming | Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A 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 = [1] Output: 1

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

Constraints: 1 <= nums.length <= 105 -104 <= nums[i] <= 104

Explanation:

**Intution**: Start traversing your array keep each element in the sum and every time keep the max of currSum and prevSum.
But the catch here is that if at any point sum becomes negative then no point keeping it because 0 is obviously greater than negative, so just make your sum 0.

Now here in this question you can see that you can also be asked some more things like :

- Length of the max subarray
- Elements of the max subarray
- Start and End index of max subarray
**This is very important concept from interview point so try to get the ans of above mentioned point and have confidence on this algorithm.**

**C++ Solution**

```
class Solution {
public:
int maxSubArray(vector<int>& A) {
int ans=A[0],i,j,sum=0;
for(i=0;i<A.size();i++){
sum+=A[i];
ans=max(sum,ans);
sum=max(sum,0);
}
return ans;
}
};
```

**Java Solution**

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