[LeetCode] Widest Pair of Indices With Equal Range Sum

1983. Widest Pair of Indices With Equal Range Sum

You are given two 0-indexed binary arrays nums1 and nums2. Find the widest pair of indices (i, j) such that i <= j and nums1[i] + nums1[i+1] + … + nums1[j] == nums2[i] + nums2[i+1] + … + nums2[j].

The widest pair of indices is the pair with the largest distance between i and j. The distance between a pair of indices is defined as j - i + 1.

Return the distance of the widest pair of indices. If no pair of indices meets the conditions, return 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int widestPairOfIndices(vector<int>& A, vector<int>& B) {
int res = 0, n = A.size();
unordered_map<int, int> mp;
mp[0] = {-1};
for(int i = 0, sum = 0; i < n; i++) {
sum += A[i] - B[i];
if(mp.count(sum)) res = max(res, i - mp[sum]);
else mp[sum] = i;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/06/PS/LeetCode/widest-pair-of-indices-with-equal-range-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.