Two neighboring orchards, Orchard A and Orchard B, each keep a daily log of how many kilograms of fruit they harvested. The co-op manager wants to find the longest unbroken run of consecutive days for which the two orchards harvested the exact same total amount of fruit over that run.
Formally, given two integer sequences of the same length representing the daily harvest of Orchard A and Orchard B, find the maximum length of a contiguous span of days [i, j] (1 <= i <= j <= n) such that the sum of Orchard A's harvest over days i..j equals the sum of Orchard B's harvest over days i..j. If no such span exists, report 0.
Line 1: a single integer n, the number of days.
Line 2: n space-separated integers, Orchard A's harvest for each day.
Line 3: n space-separated integers, Orchard B's harvest for each day.
A single integer: the maximum number of days in a contiguous span where the two orchards' cumulative harvests are equal, or 0 if no such span exists (this includes the case where not even a single day matches).
1 <= n <= 1000000 <= harvest value <= 10000 for every day in both logsExample 1
Input
5 1 2 3 4 5 5 4 3 2 1
Expected
5
Explanation
Orchard A's total over all 5 days is 1+2+3+4+5=15, and Orchard B's total is 5+4+3+2+1=15. Since the two totals already match over the entire range, the widest matching span is all 5 days, so the answer is 5.
Example 2
Input
4 1 5 2 3 4 1 2 3
Expected
2
Explanation
The full 4-day totals are 11 for Orchard A and 10 for Orchard B, which don't match, so the whole range fails. But days 3-4 give Orchard A a sum of 2+3=5 and Orchard B a sum of 2+3=5, which match, and no wider span works, so the answer is 2.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →