题解 | #乘积为正数的最长连续子数组#

乘积为正数的最长连续子数组

https://www.nowcoder.com/practice/0112b9b5a09048d89309f55ea666db91

#include <bits/stdc++.h>
using namespace std;

int main() {
   int n;
   cin >> n;
   vector<int> arr(n);
   for(int i = 0; i < n; i++) cin >> arr[i];
   vector<int> postive(n,0),negative(n,0);
   postive[0] = arr[0] > 0 ? 1 : 0;
   negative[0] = arr[0] > 0 ? 0 : 1;
   int ret = 0;
   for(int i = 1; i < n; i++){
    if(arr[i] > 0){
        postive[i] = postive[i-1] + 1;
        negative[i] = (negative[i-1]  == 0 ? 0 : negative[i-1] + 1);
    }else if(arr[i] < 0) {
        negative[i] = postive[i-1] + 1;
        postive[i] = (negative[i-1] == 0 ? 0 : negative[i-1] + 1);
    }else {
        negative[i] = 0;
        postive[i] = 0;
    }
    if(ret < postive[i]) ret = postive[i];
   }
   cout << ret << endl;
   return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务