To solve this problem, we need to count the number of valid pairs (i, j) such that i < j and (A[i] + A[j] > B[i] + B[j]).
Approach
The key insight here is to transform the problem into a more manageable form. Let's define a new array (C) where (C[k] = A[k] - B[k]). The original condition (A[i] + A[j] > B[i] + B[j]) can be rewritten as (C[i] + C[j] > 0).
Now, the problem reduces to counting the number of pairs (i, j) with i < j and (C[i] + C[j] > 0). To do this efficiently:
- Sort the array (C) in ascending order.
- Use two pointers to count valid pairs:
- Start with left at the beginning and right at the end of the sorted array.
- If (C[left] + C[right] > 0), all elements from left to right-1 will form valid pairs with right, so add the count of these elements to the result and move right leftwards.
- If (C[left] + C[right] \leq 0), move left rightwards to find a larger element that can form a valid pair with right.
Solution Code
def main():
import sys
input = sys.stdin.read().split()
ptr = 0
N = int(input[ptr])
ptr +=1
A = list(map(int, input[ptr:ptr+N]))
ptr +=N
B = list(map(int, input[ptr:ptr+N]))
C = [a - b for a, b in zip(A, B)]
C.sort()
left = 0
right = N-1
count =0
while left < right:
if C[left] + C[right] > 0:
count += right - left
right -=1
else:
left +=1
print(count)
if __name__ == "__main__":
main()
Explanation
- Transformation: By converting the problem to using array (C), we simplify the condition to checking sums of pairs in (C).
- Sorting: Sorting (C) allows us to use the two-pointer technique, which is efficient and runs in linear time after sorting.
- Two-pointer Technique: This technique helps us count valid pairs in (O(N)) time after sorting, making the overall complexity (O(N \log N)) (due to sorting), which is optimal for the given constraints.
This approach efficiently handles the problem and ensures that we count all valid pairs without missing any or counting duplicates. The solution is both time and space efficient, making it suitable for large input sizes.


(免责声明:本文为本网站出于传播商业信息之目的进行转载发布,不代表本网站的观点及立场。本文所涉文、图、音视频等资料的一切权利和法律责任归材料提供方所有和承担。本网站对此资讯文字、图片等所有信息的真实性不作任何保证或承诺,亦不构成任何购买、投资等建议,据此操作者风险自担。) 本文为转载内容,授权事宜请联系原著作权人,如有侵权,请联系本网进行删除。