Блог пользователя I_love_penny

Автор I_love_penny, история, 7 лет назад, По-английски

How to solve this problem using binary search.
Problem Statement :
You are given an array A of N integers in nondecreasing order. Remove K integers such that the maximum difference between two consecutive elements is minimized.
​​Problem Link
solution using binary search (I am not getting its intuition). ​​

  • Проголосовать: нравится
  • +5
  • Проголосовать: не нравится

»
7 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Binary search for the maximum difference, to find the minimum maximum difference we can achieve. If you won't allow differences bigger than mid, then you need to "cut" your array removing all differences from the left and right until you clear everything bigger than mid. That leaves, at best, a contiguous segment. So he's just looping to find the biggest contiguous segment that doesn't have any difference greater than mid.

»
7 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

You binary search on the answer. For checking a particular value x, you find the longest subarray of length L that has adjacent difference less than x. So you remove (n-L) elements. If this is less than K, you can decrease hi, otherwise you need to go in the right part ie increase lo.

  • »
    »
    7 лет назад, # ^ |
      Проголосовать: нравится +3 Проголосовать: не нравится

    Okay I got it , if we can get subarray by removing <=k elements than we can get subarray by removing k elements also. Thanks :)

»
7 лет назад, # |
  Проголосовать: нравится +6 Проголосовать: не нравится

You can solve this without binary search too.

You should remove k integers either from starting or ending because removing elements from the middle of the array only increases the consecutive difference and It doesn't make sense.

We start by building segment tree on the consecutive differences.

and then we iterate the array from left to right, at every index i we assume that we have removed i elements from starting and now, we need to remove k — i elements from the end.

We now query for the maximum difference in this remaining segment and the final answer would be the minimum of these queries.


Code
  • »
    »
    7 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    You can solve this without using a segment tree. Simply retain the differences in a set.

    Code
  • »
    »
    5 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    How to make changew to your code, if the first and the last elements are fixed ?