DIY: Longest Subarray With Absolute Diff Less Than Equal to Limit
Solve the interview question "Longest Subarray With Absolute Diff Less Than Equal to Limit" in this lesson.
We'll cover the following
Problem statement
You are given an array of integers, nums
, and an integer, limit
. You have to return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit
.
Input
The input will be an array of integers and a single integer limit
. The following is an example input:
nums = {10, 1, 2, 4, 7, 2}
limit = 5
Output
The output will be an integer representing the length of the longest subarray in which two elements’ difference is less than or equal to limit
. The following is an example output:
4
The subarray {2, 4, 7, 2}
is of length 4
, and the absolute difference between 7
and 2
is equal to 5
, which is within our limit
.
Coding exercise
Implement the longestSubarray(nums, limit)
function, where nums
is the array of integers and limit
is the provided limit. The function will return an integer representing the length of the longest subarray in which two elements’ difference is less than or equal to limit
.
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.