Talentd
FleetCode

4076. Longest Resilient Subarray II

Medium57.7% acceptance

You are given an integer array nums and an integer k.

A subarray is resilient if, for every position in it, deleting the element at that position leaves the remaining elements with a sum divisible by k.

For a subarray of length 1, the remaining sum is 0, which is divisible by k.

Return the length of the longest resilient subarray.

Example 1:

Input: nums = [2,4,6,3], k = 2

Output: 3

Explanation:

The subarray [2, 4, 6] sums to 12. Deleting 2, 4, or 6 leaves a sum of 10, 8, or 6, respectively, each of which is divisible by 2. Therefore, the answer is 3.

Example 2:

Input: nums = [1,4,7,1], k = 3

Output: 4

Explanation:

The subarray [1, 4, 7, 1] sums to 13. Deleting the first 1, the 4, the 7, or the last 1 leaves a sum of 12, 9, 6, or 12, respectively, each of which is divisible by 3. Therefore, the answer is 4.

Example 3:

Input: nums = [5,5,4,8], k = 4

Output: 2

Explanation:

The subarray [5, 5] is not resilient, since deleting either 5 leaves a sum of 5, which is not divisible by 4.

The subarray [4, 8] sums to 12. Deleting 4 or 8 leaves a sum of 8 or 4, respectively, each of which is divisible by 4. Therefore, the answer is 2.

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 105
  • 1 <= k <= 105

Hints open one at a time

Hint 1
If deleting any element leaves a sum divisible by k, all elements of the subarray must have the same remainder modulo k. Split the array into maximal contiguous runs of equal remainders.
Hint 2
For a run with remainder r, a subarray of length L is resilient exactly when (L - 1) * r is divisible by k.
Hint 3
Let d = k / gcd(r, k). For a run of length m, its longest resilient subarray has length 1 + floor((m - 1) / d) * d.
17:41
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def resilientSubarray(self, nums: list[int], k: int) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
[2,4,6,3]
2
Input
[1,4,7,1]
3
Input
[5,5,4,8]
4
Your code is saved on this device.Solution