-
Notifications
You must be signed in to change notification settings - Fork 0
/
Maximum Subarray Sum
70 lines (41 loc) · 1.08 KB
/
Maximum Subarray Sum
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
60
61
62
63
64
65
66
67
68
69
70
import java.util.* ;
import java.io.*;
public class Solution {
public static long maxSubarraySum(int[] arr, int n) {
long maxi=0;
long sum=0;
for(int i=0;i<n;i++){
sum+=arr[i];
if(sum<0){
sum=0;
}
if(sum>=maxi)
maxi=sum;
}
return maxi;
}
}
// write your code here
// int sum =0;
// int maxi = arr[0];
// for(int i =0; i<arr.length; i++){
// sum += arr[i];
// if(sum > maxi) maxi = sum;
// if(sum < 0) sum = 0;
// }
// return maxi;
class Solution {
public int maxSubArray(int[] nums) {
int size = nums.length;
int max_so_far = Integer.MIN_VALUE, max_ending_here = 0;
for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + nums[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
}
return max_so_far;
}
}