Longest Subarray
Array, Dynamic Sliding Window
Finds the longest subarray with sum less than or equal to k
in an array.
Solutions
Approach -Brute Force Technique
Steps
Initialize Variables: The algorithm starts by initializing a variable
maxLength
to 0. This will keep track of the length of the longest subarray found so far.Iterate Over Array: The algorithm then enters a nested loop that iterates over each possible subarray in
nums
.Calculate Subarray Sum: For each subarray, the algorithm calculates the sum of the elements in the subarray.
Check for Desired Sum: If the sum of the elements in the subarray is less than or equal to
k
, the algorithm updatesmaxLength
to be the maximum ofmaxLength
and the length of the current subarray.
Return Result: After the loops, the algorithm returns
maxLength
, which is the length of the longest subarray with a sum that does not exceedk
.
Complexity
Time complexity:
O(N^2)
Space complexity:
O(1)
Approach - Dynamic Sliding Window
This program uses two pointers, start
and end
, to represent the current subarray. It moves end
forward and adds arr[end]
to sum
. If sum
becomes more than k
, it removes elements from the start until sum
is less than or equal to k
. The maximum length of the subarrays encountered is the answer.
Steps
Initialize Variables: The algorithm starts by initializing several variables:
start
andend
to keep track of the current subarray,sum
to keep track of the sum of the current subarray, andmaxLength
to keep track of the length of the longest subarray found so far.Iterate Over Array: The algorithm then enters a loop that iterates over each element in the input array
arr
.Update Sum: For each element, the algorithm adds the element’s value to
sum
.Adjust Start of Subarray: If
sum
exceedsk
, the algorithm enters a loop that removes elements from the start of the subarray untilsum
is less than or equal tok
.Update maxLength: If
sum
is less than or equal tok
, the algorithm updatesmaxLength
to be the maximum ofmaxLength
and the length of the current subarray.Move End of Subarray: The algorithm then increments
end
to move to the next element in the array.
Return Result: After the loop, the algorithm returns
maxLength
, which is the length of the longest subarray with a sum that does not exceedk
.
Complexity
Time complexity:
O(N)
Space complexity:
O(1)
Last updated