Skip to contentKEEP THE CRAFTTHE SANCTUARY

Longest Continuous Subarray Within Limit

Find the longest subarray whose largest and smallest values differ by at most limit.

The problem

Implement Solution.longestSubarray(nums, limit). Return the length of the longest contiguous subarray in which the largest value minus the smallest value is at most limit. For example, with nums = [8, 2, 4, 7] and limit = 4 the answer is 2, from [2, 4] or [4, 7]. nums has between 1 and 100,000 values, each from 1 to 1,000,000,000, and 0 <= limit <= 1,000,000,000.

Starter code

class Solution:
    def longestSubarray(self, nums, limit):
        pass

Public examples

  1. nums = [8, 2, 4, 7], limit = 4gives2
  2. nums = [1, 3], limit = 2gives2
  3. nums = [8], limit = 0gives1

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.