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 题目总结 

  • 相关阅读:
    RabbitMQ和Kafka的区别
    如何在 Vim 中复制,剪切,粘贴
    python中的堆支持自定义的比较函数
    LLDP协议(笔记草稿)
    You may have an infinite update loop in a component render function,vue模板报错
    修改element ui样式,el-dialog__header样式,并且不影响全局
    js,小数字符串去除右边零显示
    egg-sequelize创建表
    Cyclic dependency found. Users is dependent of itself,mysql表循环依赖问题
    eggjs sequelize操作多个数据,表名不加s,不默认加创建和修改时间字段
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14284844.html
Copyright © 2011-2022 走看看