You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.
Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1.
题解
解法1 是滑动窗口暴力求解
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defminOperations(self, nums: list[int], x: int) -> int: target, size, window_sum, low, n = sum(nums) - x, -1, 0, -1, len(nums) for high, num inenumerate(nums): window_sum += num while low + 1 < n and window_sum > target: low += 1 window_sum -= nums[low] if window_sum == target: size = max(size, high - low) return -1if size < 0else n - size
解法2 是前缀和+hashmap 做索引
1 2 3 4 5 6 7 8 9 10
classSolution: defminOperations(self, nums: list[int], x: int) -> int: length, total, prefix_sum, results = len(nums), sum(nums), 0, -1 target, sum_index = total - x, {0: -1, total: length - 1} for index, value inenumerate(nums): prefix_sum += value if prefix_sum - target in sum_index: results = max(results, index - sum_index[prefix_sum - target]) sum_index[prefix_sum] = index return -1if results < 0else length - results