Skip to content

Commit 10b2eed

Browse files
authored
Create MaximumSubarray.java
1 parent 30d86b7 commit 10b2eed

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

MaximumSubarray.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
Maximum Subarray
3+
Solved
4+
5+
Given an array of integers nums, find the subarray with the largest sum and return the sum.
6+
7+
A subarray is a contiguous non-empty sequence of elements within an array.
8+
9+
Example 1:
10+
11+
Input: nums = [2,-3,4,-2,2,1,-1,4]
12+
13+
Output: 8
14+
15+
Explanation: The subarray [4,-2,2,1,-1,4] has the largest sum 8.
16+
17+
Example 2:
18+
19+
Input: nums = [-1]
20+
21+
Output: -1
22+
23+
Constraints:
24+
25+
1 <= nums.length <= 1000
26+
-1000 <= nums[i] <= 1000
27+
*/
28+
29+
class MaximumSubarray
30+
{
31+
public int maxSubArray(int[] nums)
32+
{
33+
int totalSum = nums[0];
34+
int currSum = nums[0];
35+
int n = nums.length;
36+
37+
for(int i = 1; i < n; i++)
38+
{
39+
currSum = Math.max(nums[i], currSum + nums[i]);
40+
totalSum = Math.max(totalSum, currSum);
41+
}
42+
43+
return totalSum;
44+
}
45+
}

0 commit comments

Comments
 (0)