ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 两个二进制数组中具有相同总和的最长跨度 > 原文: [https://www.geeksforgeeks.org/longest-span-sum-two-binary-arrays/](https://www.geeksforgeeks.org/longest-span-sum-two-binary-arrays/) 给定两个具有相同大小 n 的二进制数组 arr1 []和 arr2 []。 求出最长公共跨度(i,j)的长度,其中 j > = i,使得 arr1 [i] + arr1 [i + 1] +…。 + arr1 [j] = arr2 [i] + arr2 [i + 1] +…。 + arr2 [j]。 预期时间复杂度为Θ(n)。 **示例**: ``` Input: arr1[] = {0, 1, 0, 0, 0, 0}; arr2[] = {1, 0, 1, 0, 0, 1}; Output: 4 The longest span with same sum is from index 1 to 4. Input: arr1[] = {0, 1, 0, 1, 1, 1, 1}; arr2[] = {1, 1, 1, 1, 1, 0, 1}; Output: 6 The longest span with same sum is from index 1 to 6. Input: arr1[] = {0, 0, 0}; arr2[] = {1, 1, 1}; Output: 0 Input: arr1[] = {0, 0, 1, 0}; arr2[] = {1, 1, 1, 1}; Output: 1 ``` [](https://practice.geeksforgeeks.org/problem-page.php?pid=188) ## 强烈建议您在继续解决方案之前,单击此处进行练习。 **方法 1(简单解决方案)** 通过考虑两个数组的相同子数组来一一对应。 对于所有子数组,计算总和,如果总和相同且当前长度大于最大长度,则更新最大长度。 下面是 C++ 实现的简单方法。 ## C++ ```cpp // A Simple C++ program to find longest common // subarray of two binary arrays with same sum #include<bits/stdc++.h> using namespace std; // Returns length of the longest common subarray // with same sum int longestCommonSum(bool arr1[], bool arr2[], int n) {     // Initialize result     int maxLen = 0;     // One by one pick all possible starting points     // of subarrays     for (int i=0; i<n; i++)     {        // Initialize sums of current subarrays        int sum1 = 0, sum2 = 0;        // Conider all points for starting with arr[i]        for (int j=i; j<n; j++)        {            // Update sums            sum1 += arr1[j];            sum2 += arr2[j];            // If sums are same and current length is            // more than maxLen, update maxLen            if (sum1 == sum2)            {              int len = j-i+1;              if (len > maxLen)                 maxLen = len;            }        }     }     return maxLen; } // Driver program to test above function int main() {     bool  arr1[] = {0, 1, 0, 1, 1, 1, 1};     bool  arr2[] = {1, 1, 1, 1, 1, 0, 1};     int n = sizeof(arr1)/sizeof(arr1[0]);     cout << "Length of the longest common span with same "             "sum is "<< longestCommonSum(arr1, arr2, n);     return 0; } ```