将 x 减到 0 的最小操作数 Minimum Operations to Reduce X to Zero

文章目录

  • 将 x 减到 0 的最小操作数 Minimum Operations to Reduce X to Zero
  • 思路
  • Tag

将 x 减到 0 的最小操作数 Minimum Operations to Reduce X to Zero

给定一个整数数组nums和一个整数x。每一次操作时,应当删除nums的最left和最right的元素,然后从x中减去该元素的值。

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

nums = [1,1,4,2,3], x = 5
2  right【2,3】
nums = [5,6,7,8,9], x = 4
-1 没有满足条件的数
nums = [3,2,20,1,1,3], x = 10
5   left【3,2】 right【1,1,3】

思路

将x减到0的最小操作数。也就是说可能会存在左边几个数+右边几个数==X,如果存在多个可能性,那么就选择最小的数据。

统计left presum,统计right presum,从左边开始遍历,在右边寻找是否存在x-presuml[i]的j下标,不存在就返回-1。

如果存在i,j,就记录到ans,如果发现到比ans更小的(i+j),就更新ans=i+j;

public int minOperations(int[] nums, int x) {
        int[] presuml = new int[nums.length+1];
        int[] presumr = new int[nums.length+1];
        presuml[0] =0;
        presumr[0] =0;

        for (int i = 0; i < nums.length; i++) {
            presuml[i+1] = presuml[i]+nums[i];//calc presum from left
        }
        for (int i = nums.length-1; i >=0 ; i--) {
            presumr[nums.length-i] = presumr[nums.length-i-1] + nums[i];//calc presum from right
        }
        
        int ans = -1;
        //travel from left presum ,then try to find a result equal (x-presuml[i]) from right presum
        //if exist should return j
        //(i+j) maybe the result but we should check i+j bigger than length
        //if ans is bigger than (i+j),we shoule replace ans with (i+j)
        for (int i = 0; i < presuml.length; i++) {
            int j = binarysearch(presumr, x - presuml[i]);
            if(j==-1){
                continue;
            }
            if(i+j>nums.length){
                continue;
            }
            if(ans==-1||ans>(i+j)){
                ans = i+j;
            }
        }
        return ans;
    }

    public int binarysearch(int[] arr,int x){
        int head  =0 ;
        int tail = arr.length-1;
        int mid = 0;
        while (head<=tail){
            mid = (head+tail)>>1;
            if (arr[mid] == x) {
                return mid;
            }
            else if (arr[mid]<x){
                head = mid+1;
            }
            else{
                tail = mid -1;
            }
        }
        return -1;
    }

Tag

binary search prefix sum

你可能感兴趣的:(数据结构与算法)