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

Автор CPharderthanDarkSouls, история, 2 года назад, По-английски

You are given an array , can perform two operations -if the size is greater than 1 choose two distinct elements and remove both of them -or remove a single element N — 10^5 , 1 <= arr[i] <= 10^9 Find the minimum operations to make array empty. TC — N=5, arr -> 1,2,2,3,5 Output -> 3 Explanation -> (1,2) (2,3) 5

What will be the approach of this ?

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

»
2 года назад, # |
Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится
Hint 1
Hint 2
Solution
  • »
    »
    2 года назад, # ^ |
      Проголосовать: нравится +8 Проголосовать: не нравится
    Then this minimum is possible if and only if k≤N−k. More intuitively, there

    suppose k < N — k , to remove these k elements (of highest frequency) we will need another k diff elements (which will be present in this case). After removal we will be left with N — 2*k elements.
    My question is, for these remaining elements will it always be guaranteed that we can keep forming a pair of two distinct elements and thus make the arr empty in ceil [ (N-2*k)/2 ] moves ??

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

      So if the condition is satisfied, you're right that the strategy of just removing that specific element may not always work. However, the strategy of removing the two most frequent elements at each step (not just the most frequent element at the start) will work. To prove this, we assume that we have used this strategy and it doesn't work — at the end we must have >2 of the same element, Then working backward, we can show that 1) that final element will be the most frequent element at every step, 2) every step therefore removed an occurrence of that element, so 3) the initial inequality $$$k \leq N-k$$$ was not satisfied, producing a contradiction.