-
Notifications
You must be signed in to change notification settings - Fork 0
/
Maximum Subarray
60 lines (49 loc) · 1.16 KB
/
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
53
54
55
56
57
58
59
60
class Solution{
public:
vector<int> findSubarray(int a[], int n) {
// code here
int maxSum=0;
int maxStart=0;
int maxEnd=0;
int currSum=0;
int currStart=0;
for(int i=0;i<n;i++)
{
if(a[i]<0) {currSum=0;
currStart=i+1;
}
else{
currSum+=a[i];
}
if(currSum>maxSum){
maxSum=currSum;
maxStart=currStart;
maxEnd=i+1;
}
else if(currSum==maxSum)
{
int currDis=i+1-currStart;
int maxDis=maxEnd-maxStart;
if(currDis>maxDis)
{
maxStart=currStart;
maxEnd=i+1;
}
}
}
vector<int> v;
if(maxEnd==0)
{
v.push_back(-1);
}
else
{
for(int j=maxStart;j<maxEnd;j++)
{
v.push_back(a[j]);
}
}
return v;
}
};
//IT IS MODIFIED VERSION OF KADANE'S ALGORITHM WHERE IF ARR[I]<0 THEN CURRSUM=0 AND MAIN POINT TO REMEMBER WE MAKE A SUBARRAY BY MAKING A VECTOR