-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxProductSubSequence.cpp
More file actions
53 lines (43 loc) · 850 Bytes
/
Copy pathMaxProductSubSequence.cpp
File metadata and controls
53 lines (43 loc) · 850 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
// Input: nums = [2,3,-2,4]
// Output: 6
int setMax(int a, int b){
if(a > b){
return a;
}else{
return b;
}
}
int setMin(int a, int b){
if(a < b){
return a;
}else{
return b;
}
}
void swapNum(int &a, int &b){
int temp = a;
a = b;
b = temp;
}
int maxProduct(vector<int>& nums) {
int max = nums[0];
int min = nums[0];
int answer = nums[0];
for(int i = 1 ; i < nums.size() ; i++){
if(nums[0] < 0){
swapNum(max, min);
}
max = setMax(nums[i], (nums[i]*max));
min = setMin(nums[i], (nums[i]*min));
answer = setMax(answer, max);
}
return answer;
}
int main(){
vector<int> a = {1,2,4,3,-2,2};
cout << maxProduct(a);
return 0;
}