-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximum_subarray.java
More file actions
37 lines (33 loc) · 833 Bytes
/
Copy pathMaximum_subarray.java
File metadata and controls
37 lines (33 loc) · 833 Bytes
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
// https://leetcode.com/problems/maximum-subarray/
// BRUTE FORCE SOLUTION O(N^2)
class solution{
public int maxSubArray(int []nums){
int max = Integer.MIN_VALUE;
for(int i = 0;I<nums.length;i++){
int sum = 0;
for(int j = i;j<nums.length;j++){
sum += arr[j];
if(sum > max){
max = sum;
}
}
return max;
}
}
// OPTIMISED SOLUTION BY KADANE'S ALGORITHM O(N)
class Solution {
public int maxSubArray(int[] nums) {
int cursum = 0;
int maxsum = Integer.MIN_VALUE;
for(int i =0;i<nums.length;i++){
cursum = cursum + nums[i];
if(cursum > maxsum){
maxsum = cursum;
}
if(cursum<0){
cursum = 0;
}
}
return maxsum;
}
}