Minimum no of changes required to make array strictly increasing

后端 未结 5 1727
栀梦
栀梦 2021-01-01 02:51

I have a problem in which we have an array of positive numbers and we have to make it strictly increasing by making zero or more changes to the array elements.

We ar

5条回答
  •  一生所求
    2021-01-01 03:42

    inspired by the hits of @Peter de Rivaz,

    I found the key condition of this problem is : num[i]-i >= num[j]-j >= 0 (i > j).

    The following Java code (O(NlgN)) is the slight modification to the standard longest increasing subsequence algorithm, here we skip all the num[i] where num[i]-i < 0.

      static int resolve(int... nums) {
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        int right = 0;
        for (int i = 1; i < nums.length; i++) {
          if (nums[i] >= i) {
            int realNum = nums[i] - i;
            if (realNum >= dp[right]) {
              right++;
              dp[right] = realNum;
            } else {
              dp[binarySearch(dp, 0, right, realNum)] = realNum;
            }
          }
        }
        return nums.length - (right + 1);
      }
    
      static int binarySearch(int[] nums, int left, int right, int key) {
        while (left <= right) {
          int mid = (left + right) >>> 1;
          if (nums[mid] > key) {
            right = mid - 1;
          } else {
            left = mid + 1;
          }
        }
        return left;
      }
    

提交回复
热议问题