Untitled
public class MinOperationsToReduceX { public int minOperations(int[] nums, int x) { // Step 1: Calculate the total sum of the array int totalSum = 0; for (int num : nums) { totalSum += num; } // Step 2: Determine the target sum for the sliding window int target = totalSum - x; // If target is negative, it's impossible to achieve the result if (target < 0) return -1; // Step 3: Initialize variables for the sliding window int maxLength = -1; // Longest subarray with sum equal to target int currentSum = 0; // Running sum of the current window int i = 0; // Left pointer int j = 0; // Right pointer // Step 4: Traverse the array using a while loop while (j < nums.length) { // Expand the window: add nums[j] to the current sum currentSum += nums[j]; // Shrink the window from the left if currentSum exceeds target while (currentSum > target) { currentSum -= nums[i]; i++; // Move the left pointer } // Update maxLength if a valid subarray is found if (currentSum == target) { maxLength = Math.max(maxLength, j - i + 1); } // Move the right pointer j++; } // Step 5: Calculate the result // If maxLength is -1, no valid subarray was found return maxLength == -1 ? -1 : nums.length - maxLength; } public static void main(String[] args) { MinOperationsToReduceX solution = new MinOperationsToReduceX(); // Test Case 1 System.out.println(solution.minOperations(new int[]{1, 1, 4, 2, 3}, 5)); // Output: 2 // Test Case 2 System.out.println(solution.minOperations(new int[]{5, 6, 7, 8, 9}, 4)); // Output: -1 // Test Case 3 System.out.println(solution.minOperations(new int[]{3, 2, 20, 1, 1, 3}, 10)); // Output: 5 } }
Leave a Comment