-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximum Subarray.cpp
More file actions
82 lines (63 loc) · 1.28 KB
/
Maximum Subarray.cpp
File metadata and controls
82 lines (63 loc) · 1.28 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
int maxSubArray(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> processed;
int signflag = -1;
int sum = 0;
int result = INT_MIN;
for(int i=0; i<n; i++)
{
if(A[i] >= 0 && signflag == -1)
{
if(sum != 0)
processed.push_back(sum);
sum = 0;
signflag = 1;
}else if(A[i] <0 && signflag == 1)
{
if(sum != 0)
processed.push_back(sum);
sum = 0;
signflag = -1;
}
if(A[i]>result)
result = A[i];
sum += A[i];
}
processed.push_back(sum);
int* sumArr = new int[n];
for(int i=0; i<processed.size(); i++)
sumArr[i] = 0;
for(int i=0; i<processed.size(); i++)
{
sumArr[i] = processed[i];
if(processed[i] > result)
result = processed[i];
}
for(int i=2; i<=processed.size(); i++)
{
int sum = 0;
for(int j=0; j+i-1<processed.size();j++)
{
sumArr[j] = sumArr[j] + processed[j+i-1];
if(sumArr[j] > result)
result = sumArr[j];
}
}
return result;
}
};
//void main()
//{
// int A[] = {1,2,-1,-2,2,1,-2,1,4,-5,4};
//
// Solution s;
// cout<<s.maxSubArray(A, 11)<<endl;
// getchar();
//}