原文链接: https://leetcode-cn.com/problems/minimum-operations-to-reduce-x-to-zero
英文原文
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
.
Example 1:
Input: nums = [1,1,4,2,3], x = 5 Output: 2 Explanation: The optimal solution is to remove the last two elements to reduce x to zero.
Example 2:
Input: nums = [5,6,7,8,9], x = 4 Output: -1
Example 3:
Input: nums = [3,2,20,1,1,3], x = 10 Output: 5 Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 104
1 <= x <= 109
中文题目
给你一个整数数组 nums
和一个整数 x
。每一次操作时,你应当移除数组 nums
最左边或最右边的元素,然后从 x
中减去该元素的值。请注意,需要 修改 数组以供接下来的操作使用。
如果可以将 x
恰好 减到 0
,返回 最小操作数 ;否则,返回 -1
。
示例 1:
输入:nums = [1,1,4,2,3], x = 5 输出:2 解释:最佳解决方案是移除后两个元素,将 x 减到 0 。
示例 2:
输入:nums = [5,6,7,8,9], x = 4 输出:-1
示例 3:
输入:nums = [3,2,20,1,1,3], x = 10 输出:5 解释:最佳解决方案是移除后三个元素和前两个元素(总共 5 次操作),将 x 减到 0 。
提示:
1 <= nums.length <= 105
1 <= nums[i] <= 104
1 <= x <= 109
通过代码
高赞题解
本题类似186周周赛的第二题可获得的最大点数,找外部最小即找中间最大
class Solution {
public int minOperations(int[] nums, int x) {
// 使用滑动窗口找中间最长的片段使得sum(片段)=sum(nums)-x
int maxPart = -1;
int sum = Arrays.stream(nums).sum();
int currentSum = 0;
int left = 0;
int right = 0;
while (left < nums.length) {
// 如果右边未到尽头,不断先向右探测片段,如果大于目标sum-x则左边移动直到结束
if (right < nums.length) {
currentSum += nums[right++];
}
while (currentSum > sum - x && left < nums.length) {
currentSum -= nums[left++];
}
if (currentSum == sum - x) {
maxPart = Math.max(maxPart, right - left);
}
if (right == nums.length) {
left++;
}
}
return maxPart == -1 ? -1 : nums.length - maxPart;
}
}
统计信息
通过次数 | 提交次数 | AC比率 |
---|---|---|
9561 | 31458 | 30.4% |
提交历史
提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
---|