题解 | #乘积为正数的最长连续子数组#
乘积为正数的最长连续子数组
https://www.nowcoder.com/practice/0112b9b5a09048d89309f55ea666db91
#include <any> #include <iostream> #include <utility> using namespace std; int main() { int max_l = 0, min_l = 0, max_dp = 1, min_dp = 1; int n, a; cin >> n; int ans = 0; for (int i = 0; i < n; i++) { cin >> a; if (a == 0) { // 重置 max_l = 0, min_l = 0, max_dp = 1, min_dp = 1; } else if (a < 0) { a = -1; // 简化防止溢出 swap(max_dp, min_dp); // 交换最大最小 swap(max_l, min_l); } else { a = 1; } if (max_dp * a > 0) { max_l++; max_dp *= a; } else { // 重置 max_l = 0; max_dp = 1; } if (min_dp * a < 0) { min_l++; min_dp *= a; } else { // 重置 min_l = 0; min_dp = 1; } // cout << "max_l: " << max_l << " min_l: " << min_l << endl; ans = max(ans, max_l); } cout << ans; } // 64 位输出请用 printf("%lld")