题解 | #乘积为正数的最长连续子数组#
乘积为正数的最长连续子数组
http://www.nowcoder.com/practice/0112b9b5a09048d89309f55ea666db91
参考大佬们的代码,维护两个数据代表含当前数乘积为正数和负数的最大长度
#include <vector>
#include <iostream>
using namespace std;
int MaxLengthinVec(vector<int> &vec){
int ret = 0;
int positive, negetive, Temp;
positive = (vec[0] > 0) ? 1 : 0;
negetive = (vec[0] < 0) ? 1 : 0;
for(int i = 1; i < vec.size(); i++){
if(vec[i] > 0){
positive = positive + 1;
negetive = negetive > 0 ? negetive + 1 : 0;
}
else if(vec[i] == 0){
positive = 0;
negetive = 0;
}
else{
Temp = negetive > 0 ? negetive + 1 : 0;
negetive = positive + 1;
positive = Temp;
}
ret = max(ret, positive);
}
return ret;
}
int main(){
int Num, val, ret;
cin >> Num;
vector<int> vec;
while(Num--){
cin >> val;
vec.push_back(val);
}
ret = MaxLengthinVec(vec);
cout << ret << endl;
return 0;
}