forked from prakashshuklahub/Interview-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
53 Maximum Subarray
52 lines (41 loc) · 1.38 KB
/
53 Maximum Subarray
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
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
*********Brute Force Solution **************
public int maxSubArray(int[] nums) {
int max = Integer.MIN_VALUE;
for(int i=0;i<nums.length;i++){ //1 2 3 4
for(int j=i;j<nums.length;j++){
int sum = 0;
for(int k=i;k<=j;k++){
sum = sum+nums[k];
}
max = Math.max(sum,max);
}
}
return max;
}
*********Optimize 1 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 = sum + nums[j];
max = Math.max(sum,max);
}
}
return max;
}
*********Optimize 2 Solution **************
public int maxSubArray(int[] nums) {
int bestsum = Integer.MIN_VALUE;
int currentsum = 0;
for(int i=0;i<nums.length;i++) {
currentsum = Math.max(nums[i],currentsum+nums[i]);
bestsum = Math.max(bestsum,currentsum);
}
return bestsum;
}