- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 60 lines of Java from the credited upstream file 2071.java.
- The implementation visibly relies on sequence storage, ordered lookup.
- 3 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int maxTaskAssign(int[] tasks, int[] workers, int pills, int strength) {3 int ans = 0;4 int l = 0;5 int r = Math.min(tasks.length, workers.length);6 7 Arrays.sort(tasks);8 Arrays.sort(workers);9 10 while (l <= r) {11 final int m = (l + r) / 2;12 if (canComplete(tasks, workers, pills, strength, m)) {13 ans = m;14 l = m + 1;15 16 } else {17 r = m - 1;18 }19 }20 21 return ans;22 }23 24 25 private boolean canComplete(int[] tasks, int[] workers, int pillsLeft, int strength, int k) {26 27 TreeMap<Integer, Integer> sortedWorkers = new TreeMap<>();28 for (int i = workers.length - k; i < workers.length; ++i)29 sortedWorkers.merge(workers[i], 1, Integer::sum);30 31 32 for (int i = k - 1; i >= 0; --i) {33 34 Integer lo = sortedWorkers.ceilingKey(tasks[i]);35 if (lo != null) {36 sortedWorkers.merge(lo, -1, Integer::sum);37 if (sortedWorkers.get(lo) == 0) {38 sortedWorkers.remove(lo);39 }40 } else if (pillsLeft > 0) {41 42 lo = sortedWorkers.ceilingKey(tasks[i] - strength);43 if (lo != null) {44 sortedWorkers.merge(lo, -1, Integer::sum);45 if (sortedWorkers.get(lo) == 0) {46 sortedWorkers.remove(lo);47 }48 --pillsLeft;49 } else {50 return false;51 }52 } else {53 return false;54 }55 }56 57 return true;58 }59}60