Problem · Sliding Window
Longest Subarray
A subarray of an array is defined as a contiguous block of a’s elements having a length that is less than or equal to the length of the array. For example, the subarray of array a = [1, 2, 3] are [1], [2], [3], [1, 2], [2,3], and [1, 2, 3] . Given an integer, k = 3 , the subarrays having elements that sum to a number <= k are [1], [2], and [1, 2]. The longest of these subarrays is [1, 2], which has a length of 2. Given an array, a, determine its longest subarray that sums to less than or equal to a given value k.
Complete the function maxLength in the editor. The function must return an integer that represents the length of the longest subarray of a that sums to a number <= k.
maxLength has the following parameter(s):
a[a[0],...a[n - 1]]: an array of integersk: an integer Examples
01 · Example 1
a = [3, 1, 2, 3] k = 4 return = 2
The subarrays of [1, 2, 3] having elements that sum to a number <= (k = 4) are [1], [2], [3] and [1, 2]. The longest of these is [1, 2], which has a length of 2. Return 2 as the answer.
Constraints
1 <= n <= 1051 <= a[i] <= 1031 <= k <= 109More Goldman Sachs problems
public int longestSubarray(int[] a, int k) {
// write your code here
}
a[3, 1, 2, 3]
k4
expected2
checking account