-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathMaximum Subarray Sum
More file actions
59 lines (53 loc) · 1.73 KB
/
Maximum Subarray Sum
File metadata and controls
59 lines (53 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
Maximum Subarray Sum
You are given an array (ARR) of length N, consisting of integers. You have to find the sum of the subarray (including empty subarray) having maximum sum among all subarrays.
A subarray is a contiguous segment of an array. In other words, a subarray can be formed by removing 0 or more integers from the beginning, and 0 or more integers from the end of an array.
Note :
The sum of an empty subarray is 0.
Input Format :
The first line of input contains an integer N, representing the length of the array.
The second line of input contains N single space-separated integers, denoting the elements of the array.
Output Format :
In the only output line, output the maximum subarray sum.
Note :
You are not required to print the output explicitly, it has already been taken care of. Just implement the function.
Constraints :
1 <= N <= 10^6
-10^6 <= A[i] <= 10^6
where N is the length of the array.
A[i] represents the numbers present in the array.
Time limit: 1sec
Sample Input 1 :
9
1 2 7 -4 3 2 -10 9 1
Sample Output 1 :
11
Explanation for Sample 1 :
The subarray yielding maximum sum is [1, 2, 7, -4, 3, 2].
Sample Input 2 :
6
10 20 -30 40 -50 60
Sample Input 2 :
60
Sample Input 3 :
3
-3 -5 -6
Sample Input 3 :
0
////////////////////////////////////// code in java ///////////////////////////
import java.util.* ;
import java.io.*;
public class Solution {
public static long maxSubarraySum(int[] arr, int n) {
{
long maxSoFar = 0;
long maxEndingHere = 0;
for (int i: arr)
{
maxEndingHere = maxEndingHere + i;
maxEndingHere = Math.max(maxEndingHere, 0);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
}
}