- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 89 lines of Java from the credited upstream file 3013.java.
- The implementation visibly relies on sequence storage, ordered lookup.
- 4 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Multiset {2 public void add(int num) {3 map.merge(num, 1, Integer::sum);4 ++sz;5 }6 7 public void remove(int num) {8 map.merge(num, -1, Integer::sum);9 if (map.get(num) == 0)10 map.remove(num);11 --sz;12 }13 14 public int min() {15 return map.firstEntry().getKey();16 }17 18 public int max() {19 return map.lastEntry().getKey();20 }21 22 public int size() {23 return sz;24 }25 26 public boolean contains(int num) {27 return map.containsKey(num);28 }29 30 private TreeMap<Integer, Integer> map = new TreeMap<>();31 private int sz = 0;32}33 34class Solution {35 public long minimumCost(int[] nums, int k, int dist) {36 37 38 long windowSum = 0;39 Multiset selected = new Multiset();40 Multiset candidates = new Multiset();41 42 for (int i = 1; i <= dist + 1; ++i) {43 windowSum += nums[i];44 selected.add(nums[i]);45 }46 47 windowSum = balance(windowSum, selected, candidates, k);48 long minWindowSum = windowSum;49 50 for (int i = dist + 2; i < nums.length; ++i) {51 final int outOfScope = nums[i - dist - 1];52 if (selected.contains(outOfScope)) {53 windowSum -= outOfScope;54 selected.remove(outOfScope);55 } else {56 candidates.remove(outOfScope);57 }58 if (nums[i] < selected.max()) { 59 windowSum += nums[i];60 selected.add(nums[i]);61 } else {62 candidates.add(nums[i]);63 }64 windowSum = balance(windowSum, selected, candidates, k);65 minWindowSum = Math.min(minWindowSum, windowSum);66 }67 68 return nums[0] + minWindowSum;69 }70 71 72 73 private long balance(long windowSum, Multiset selected, Multiset candidates, int k) {74 while (selected.size() < k - 1) {75 final int minCandidate = candidates.min();76 windowSum += minCandidate;77 selected.add(minCandidate);78 candidates.remove(minCandidate);79 }80 while (selected.size() > k - 1) {81 final int maxSelected = selected.max();82 windowSum -= maxSelected;83 selected.remove(maxSelected);84 candidates.add(maxSelected);85 }86 return windowSum;87 }88}89