Skip to content

Commit 0128197

Browse files
Merge pull request #331 from sagar-monga/sagar-monga
Added Solution for MaximumSubarray.java
2 parents 075d88e + 07e15d7 commit 0128197

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

LeetCode/MaximumSubarray.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
Question Link - https://leetcode.com/problems/maximum-subarray/
3+
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
4+
A subarray is a contiguous part of an array.
5+
Example 1:
6+
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
7+
Output: 6
8+
Explanation: [4,-1,2,1] has the largest sum = 6.
9+
Example 2:
10+
Input: nums = [1]
11+
Output: 1
12+
Example 3:
13+
Input: nums = [5,4,-1,7,8]
14+
Output: 23
15+
Constraints:
16+
1 <= nums.length <= 105
17+
-104 <= nums[i] <= 104
18+
*/
19+
20+
class Solution {
21+
public int maxSubArray(int[] nums) {
22+
int max = nums[0];
23+
int maxOverall = nums[0]; // Assigning first element as maximum
24+
25+
// if upon adding the current element,
26+
// we find that the sum exceeds the maximum sum,
27+
// we add the current element to the longest subsequence.
28+
// Otherwise, drop the previous sum, and replace it
29+
// with the current element instead.
30+
31+
for (int i=1; i<nums.length; i++) {
32+
max = Math.max(nums[i], max + nums[i]);
33+
maxOverall = Math.max(maxOverall, max);
34+
}
35+
return maxOverall;
36+
}
37+
}

0 commit comments

Comments
 (0)