mediumArraysPattern: Two Pointers

Max Cumulative Intervals Solution

Problem Statement

Given two arrays of integers, `signal1` and `signal2`, determine the maximum number of intervals where the cumulative amplitude of the combined signals does not exceed 427.

Examples

Example 1:
Input:[1, 2, 3], [4, 5, 6]
Output:3
Explanation: The cumulative amplitude of the combined signals for all intervals is 1+4=5, 2+5=7, and 3+6=9, which are all less than 427.
Example 2:
Input:[-1, 0, 1], [2, -3, 4]
Output:3
Explanation: The cumulative amplitude of the combined signals for all intervals is -1+2=1, 0-3=-3, and 1+4=5, which are all less than 427.
Example 3:
Input:[100, 200, 300], [400, 500, 600]
Output:0
Explanation: The cumulative amplitude of the combined signals for all intervals exceeds 427.

Constraints

  • 1 <= signal1.length, signal2.length <= 10^5
  • -10^9 <= signal1[i], signal2[i] <= 10^9
  • The cumulative amplitude of the combined signals is calculated as the sum of the corresponding elements in the two arrays.
Time: O(n) Space: O(1)
The optimized approach involves using a two-pointer technique to iterate through the arrays and keeping track of the cumulative amplitude of the combined signals.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

def max_cumulative_intervals(signal1, signal2): max_intervals = 0 curr_amplitude = 0 left = 0 for right in range(len(signal1)): curr_amplitude += signal1[right] + signal2[right] while curr_amplitude > 427 and left <= right: curr_amplitude -= signal1[left] + signal2[left] left += 1 max_intervals = max(max_intervals, right - left + 1) return max_intervals