Maximum power in N levels from K such that defeating boss at level A[i] increases power by B[i]
Given two arrays a[] and b[] of size N and an integer K. The task is to find the maximum power that can be achieved in N levels with initial power K such that after defeating the ith level boss of strength a[i], power is increased by b[i]. In order to defeat a boss the power should be greater than or equal to his power.
Examples:
Input: N = 3, K = 10, a[] = {20, 30, 10}, b[] = {9, 100, 10}
Output: 29
Explanation: First defeat boss at index 3, the power becomes 20, then defeat boss at index 1 and the power becomes 29. Now you can’t defeat any other boss, so 29 is the maximum power you can achieve.
Input: N = 2, K = 5, a[] = {7, 10}, b[] = {100, 20}
Output: 5
Approach: The task can be solved using the greedy approach. Find the weakest boss and check if your power is greater than or equal to his power. If yes, then defeat the boss and take the magic box i which will increase your power by b[i]. Keep on repeating this step until there is no magic box left to take or you can’t defeat the weakest boss. Follow the below steps to solve the problem:
- Finding the weakest boss can be done easily using a minimum priority queue. Note that we will store the values in the priority queue in pairs i.e. {a[i], b[i]} so that the weakest boss is always on top in the priority queue.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the maximum power you can achieve.int maxPower(int a[], int b[], int n, int k){ priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq; for (int i = 0; i < n; i++) pq.push({ a[i], b[i] }); int cur_power = k; while (!pq.empty()) { int guard_power = pq.top().first; int extra_power = pq.top().second; pq.pop(); // The weakest guard has more power than you. if (guard_power > cur_power) break; // Defeat the current guard // and add extra power // to your current power. cur_power += extra_power; } return cur_power;} // Driver functionint main(){ int a[] = { 20, 30, 10 }; int b[] = { 9, 100, 10 }; int n = sizeof(a) / sizeof(a[0]); int k = 10; // Function Call cout << maxPower(a, b, n, k); return 0;} |
29
Time Complexity: O(N log(N))
Auxiliary Space: O(N)


.png)