826. Most Profit Assigning Work
Approach
Sort jobs by difficulty, workers by skill; use a pointer to track the max profit achievable at each skill level.
Key Techniques
Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.
The two-pointer technique places pointers at different positions (often the two ends) and moves them toward each other. It turns O(n²) nested loops into O(n) sweeps for problems like pair sums, removing duplicates, and container capacity. Works best on sorted or partitioned arrays.
Binary search reduces search space by half each step, giving O(log n) time. Beyond sorted arrays, apply it on the answer space ("binary search on result") when you can define a monotonic predicate — e.g., "can we achieve X with k resources?"
// Approach: Sort jobs by difficulty, workers by skill; use a pointer to track the max profit achievable at each skill level.
// Time: O(n log n) Space: O(n)
public class Solution {
public int MaxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {
int ans = 0;
List<int[]> jobs = new List<int[]>();
for(int i = 0; i < difficulty.Length; i++)
jobs.Add(new int[] {difficulty[i], profit[i]});
jobs.Sort((a, b) => a[0].CompareTo(b[0]));
Array.Sort(worker);
int j = 0, maxProfit = 0;
foreach(int w in worker)
{
for(; j < jobs.Count && w >= jobs[j][0]; j++)
maxProfit = Math.Max(maxProfit, jobs[j][1]);
ans += maxProfit;
}
return ans;
}
}