题解 (C语言)
未排序数组中累加和为给定值的最长子数组系列问题补1
https://www.nowcoder.com/practice/545544c060804eceaed0bb84fcd992fb
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXN 100001 int max(int a, int b) { return a > b ? a : b; } int main() { int n; scanf("%d", &n); int arr[n]; for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } for (int i = 0; i < n; i++) { if (arr[i] > 0) { arr[i] = 1; } else if (arr[i] < 0) { arr[i] = -1; } } int* prefixSumIndex = (int*)malloc((2 * n + 1) * sizeof(int)); memset(prefixSumIndex, -1, (2 * n + 1) * sizeof(int)); int sum = n; int maxLength = 0; prefixSumIndex[sum] = 0; for (int i = 0; i < n; i++) { sum += arr[i]; if (prefixSumIndex[sum] != -1) { maxLength = max(maxLength, i - prefixSumIndex[sum] + 1); } else { prefixSumIndex[sum] = i + 1; } } printf("%d\n", maxLength); free(prefixSumIndex); return 0; }