Luck Balance

Lena is preparing for an important coding competition that is preceded by a number of sequential preliminary contests. Initially, her luck balance is 0. She believes in "saving luck", and wants to check her theory. Each contest is described by two integers,  and :

  •  is the amount of luck associated with a contest. If Lena wins the contest, her luck balance will decrease by L[i] ; if she loses it, her luck balance will increase by L[i].
  •  denotes the contest's importance rating. It's equal to 1 if the contest is important, and it's equal to 0 if it's unimportant.

If Lena loses no more than k important contests, what is the maximum amount of luck she can have after competing in all the preliminary contests? This value may be negative.

Example:

Input:  k = 3,  contests=[[5,1],[2,1],[1,1],[8,1],[10,0],[5,0]]
Output: 29

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int luckBalance(int kvector<vector<int>> contests)
{
    sort(contests.begin(), contests.end());

    int ans = 0;
    int n = contests.size();
    for (int i = n - 1i >= 0i--)
    {
        if (k > 0)
        {
            if (contests[i][1] == 1)
            {
                k--;
                ans += contests[i][0];
            }
            else
                ans += contests[i][0];
        }
        else
        {
            if (contests[i][1] == 1)
                ans -= contests[i][0];
            else
                ans += contests[i][0];
        }
    }
    return ans;
}
int main()
{
    int k = 3;
    vector<vector<int>> contests = {{51}, {21}, {11},
                                    {81}, {100}, {50}};

    cout << luckBalance(kcontests);
    return 0;
}


No comments:

Post a Comment