public static int MinimumNumberOfBoats_UdemySolution(int[] weights, int maxWeight, int weightDiff) { // * the solution provided by the instructor doesn't take edge cases into account. Had to add them by had. // * algo on the last if, i had to add a comparison, since the top.key && i might be the same, and if !isTaken[i] // * that value is never popped // * this solution seems overly complicated, since every solution works for every other lower solution int n = weights.Length; if (n == 0) { return(0); } if (n == 1) { if (weights[0] <= weightDiff) { return(1); } return(0); } Array.Sort(weights); int ans = 0; int p = 0; List <bool> isTaken = new List <bool>(new bool[n]); MaxHeap <BoatKey> pq = new MaxHeap <BoatKey>(); for (int i = n - 1; i >= 0; i--) { while (p < i && weights[p] + weights[i] <= maxWeight) { pq.Insert(new BoatKey(p, weights[p])); p++; } if (isTaken[i]) { continue; } while (!pq.IsEmpty() && weights[i] - pq.Top().Weight <= weightDiff) { if (isTaken[pq.Top().Key] || i == pq.Top().Key) { pq.RemoveTop(); continue; } isTaken[i] = isTaken[pq.Top().Key] = true; pq.RemoveTop(); break; } ans++; } return(ans); }
public static int MonsterKiller(int[] dmg, int hp, int potions) { if (dmg.Length == 0) { return(0); } MaxHeap <int> kills = new MaxHeap <int>(); int i = 0; int l = dmg.Length; while (hp > 0 && i < l) { if (dmg[i] > hp) { if (potions == 0) { return(i); } else { potions--; if (!kills.IsEmpty()) { if (dmg[i] <= kills.Top()) { hp += kills.RemoveTop(); kills.Insert(dmg[i]); } } } } else { hp -= dmg[i]; if (dmg[i] > 0) { kills.Insert(dmg[i]); } } i++; } return(i); }