Sometimes it is easier to solve the inverse of the problem
I thought this problem was very tricky - I had to read the hints and even spy at some comments to see how to tackle it: https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/
My first attempt was to do exactly what the problem suggests: try all the possibilities. Of course I ran into TLE (Time Limit Exceeded) since we're talking about O(2^100000).
Reading the hints and some comments, it was clear that the strategy should be a little inverse of what the problem is asking: instead of looking for the extremes summing up to X, we should be looking for the longest sub-array adding up to Sum(Array) - X. Basically if you find that array, the answer will be straightforward (len of the array - len of the longest sub-array adding up to Sum(Array) - X).
Now to find the longest sub-array adding up to a certain number N, one can use the two pointers approach (left and right) in a sliding window. That's actually linear time and space. But to be honest I'd have never had that insight... code is below, cheers, ACC.
public int MinOperations(int[] nums, int x) { if (x > nums.Sum()) return -1; if (x == nums.Sum()) return nums.Length; int target = nums.Sum() - x; int longestPath = 0; int left = 0; int right = 0; int currentSum = nums[left]; while (left < nums.Length && right < nums.Length) { if (currentSum <= target) { if(currentSum == target) longestPath = Math.Max(longestPath, right - left + 1); right++; if (right < nums.Length) currentSum += nums[right]; } else { currentSum -= nums[left]; left++; } } if (longestPath == 0) return -1; return nums.Length - longestPath; }
Comments
Post a Comment