来自 K 的 N 级中的最大功率,使得在 A[i] 级击败老板会增加 B[i] 的功率
给定两个大小为N的数组a[]和b[]和一个整数K 。任务是找到初始功率为K的N级可以达到的最大功率,使得在击败强度为 a[i]的第 i级 BOSS 后,功率增加b[i] 。为了击败老板,权力应该大于或等于他的权力。
例子:
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
方法:可以使用贪心方法来解决任务。找到最弱的老板,检查你的力量是否大于或等于他的力量。如果是,则击败老板并获得魔法盒 i ,这将使您的力量增加b[i] 。继续重复此步骤,直到没有魔盒可取,或者您无法击败最弱的老板。请按照以下步骤解决问题:
- 使用最小优先级队列可以轻松找到最弱的老板。请注意,我们会将值成对存储在优先级队列中,即 {a[i], b[i]} 以便最弱的老板总是在优先级队列中位于顶部。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the maximum power you can achieve.
int maxPower(int a[], int b[], int n, int k)
{
priority_queue, vector >,
greater > >
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 function
int 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
时间复杂度: O(N log(N))
辅助空间: O(N)