To find the minimum removals required to achieve a target sum k by removing elements from either end of an array, three approaches can be utilized. The naive approach uses recursion to explore all combinations of removals, calculating the sum for every possible path. Though straightforward, this method is highly inefficient with O(2^n) time complexity. A better approach leverages prefix arrays and hash maps to determine the longest subarray with a sum equal to total sum−k, reducing the problem to O(n) time complexity but requiring O(n) space for storing prefix sums.
The optimized solution employs the sliding window technique, which uses two pointers to dynamically adjust a window representing the longest subarray with the desired sum. By maintaining a current sum and adjusting the window size, this method achieves O(n) time complexity and O(1) space usage. It ensures efficient computation by incrementing or decrementing the window while tracking the longest valid subarray. The result is derived as the difference between the array's size and the maximum subarray length found.
For more details, please go through - Minimum Removals for Target Sum