zoukankan      html  css  js  c++  java
  • [LeetCode] 1658. 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's 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

    将 x 减到 0 的最小操作数。

    给你一个整数数组 nums 和一个整数 x 。每一次操作时,你应当移除数组 nums 最左边或最右边的元素,然后从 x 中减去该元素的值。请注意,需要 修改 数组以供接下来的操作使用。

    如果可以将 x 恰好 减到 0 ,返回 最小操作数 ;否则,返回 -1 。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/minimum-operations-to-reduce-x-to-zero
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    思路是前缀和。首先我们处理一下目标值x,因为题目问的其实是数组中间的某个子数组,满足其数组和 = 数组全部数字的和 - 两边某一些数字,所以我们先把目标值定为 -x,这样当我们用前缀和的思路找到一个符合要求的子数组的时候,这个子数组已经等于数组所有数字的和 - x了。

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public int minOperations(int[] nums, int x) {
     3         int target = -x;
     4         int len = nums.length;
     5         for (int num : nums) {
     6             target += num;
     7         }
     8         // corner case
     9         if (target == 0) {
    10             return len;
    11         }
    12         // normal case
    13         int res = Integer.MIN_VALUE;
    14         int sum = 0;
    15         HashMap<Integer, Integer> map = new HashMap<>();
    16         map.put(0, -1);
    17         for (int i = 0; i < len; i++) {
    18             sum += nums[i];
    19             if (map.containsKey(sum - target)) {
    20                 res = Math.max(res, i - map.get(sum - target));
    21             }
    22             map.put(sum, i);
    23         }
    24         return res == Integer.MIN_VALUE ? -1 : len - res;
    25     }
    26 }

    LeetCode 题目总结 

  • 相关阅读:
    C#学习笔记---基础入门(二)
    微软Hololens设备 浅分析
    phpstorm 破解方法
    iOS 审核被拒,日志中找不到苹果返回的creashlog的解决办法
    flutter学习之添加第三方应用
    MAC flutter初步学习
    python Django 连接数据库失败的解决方法
    Python之学习菜鸟教程踩的坑
    Python学习之环境搭建
    tableView reload 不闪动方法
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14284844.html
Copyright © 2011-2022 走看看