-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq121.cpp
More file actions
62 lines (56 loc) · 1.46 KB
/
q121.cpp
File metadata and controls
62 lines (56 loc) · 1.46 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
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
class Solution {
private:
vector<int> diff;
public:
int maxProfit(vector<int>& prices) {
//construct difference vector
// cout << "hello!!!" << endl;
if (prices.size() == 0) {
// cout << "prices.size(): " << prices.size() <<endl;
return 0;
// cout << "hello again!" << endl;
}
else diff = vector<int>(prices.size(),0);
for(auto b = prices.begin()+1, b1 = diff.begin() + 1; b != prices.end(); ++b, ++b1){
cout << "*b: " << *b <<endl;
*b1 = *b - *(b-1);
cout << "*b becomes: " << *b << endl;
}
cout << "diff: ";
for(auto x:diff){
cout << x << " ";
}
cout << endl;
return FindMP(0, diff.size()-1);
}
int MaxMid(int s, int t){//s and t inclusive
int n = (s+t)/2;
int sum1 = 0, max1 = 0;
for(int i = n; i >= s; --i){
sum1 += diff[i];
if(sum1 > max1) max1 = sum1;
}
int sum2 = 0, max2 = 0;
for(int i = n + 1; i <= t; ++i){
sum2 += diff[i];
if(sum2 > max2) max2 = sum2;
}
return max(max1,max2);
}
int FindMP(int i, int j){// i and j inclusive
if(i == j) return max(0, diff[i]);
else{
int n = (i+j)/2;
return max(max(FindMP(i,n), MaxMid(i,j)),FindMP(n+1,j));
}
}
};
int main(){
Solution sol;
vector<int> a{};
cout << sol.maxProfit(a) << endl;
}