- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 86 lines of Java from the credited upstream file 3422.java.
- The implementation visibly relies on sequence storage, ordered lookup.
- 4 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class SumMultiset {2 public TreeMap<Integer, Integer> nums = new TreeMap<>();3 public long sum = 0;4 public int size = 0;5 6 public void insert(int val) {7 nums.merge(val, 1, Integer::sum);8 sum += val;9 ++size;10 }11 12 public void erase(int val) {13 nums.merge(val, -1, Integer::sum);14 if (nums.get(val) == 0)15 nums.remove(val);16 sum -= val;17 --size;18 }19}20 21class MedianTracker {22 public MedianTracker(int k) {23 this.k = k;24 }25 26 public void add(int val) {27 below.insert(val);28 balance();29 }30 31 public void remove(int val) {32 if (below.nums.containsKey(val))33 below.erase(val);34 else35 above.erase(val);36 }37 38 public long getCost() {39 return above.sum - below.sum - (k % 2 == 1 ? above.nums.firstKey() : 0L);40 }41 42 private SumMultiset below = new SumMultiset();43 private SumMultiset above = new SumMultiset();44 private int k;45 46 private void balance() {47 48 while (below.size > k / 2) {49 final int mx = below.nums.lastKey();50 below.erase(mx);51 above.insert(mx);52 }53 54 55 while (!above.nums.isEmpty()) {56 final int mx = below.nums.lastKey();57 final int mn = above.nums.firstKey();58 if (mx <= mn)59 break;60 below.erase(mx);61 above.erase(mn);62 below.insert(mn);63 above.insert(mx);64 }65 }66}67 68class Solution {69 public long minOperations(int[] nums, int k) {70 MedianTracker tracker = new MedianTracker(k);71 72 for (int i = 0; i < k; ++i)73 tracker.add(nums[i]);74 75 long ans = tracker.getCost();76 77 for (int i = k; i < nums.length; ++i) {78 tracker.remove(nums[i - k]);79 tracker.add(nums[i]);80 ans = Math.min(ans, tracker.getCost());81 }82 83 return ans;84 }85}86