Skip to content
TheCScience
TheCScience
  • Home
  • Human values
  • NCERT Solutions
  • HackerRank solutions
    • HackerRank Algorithms problems solutions
    • HackerRank C solutions
    • HackerRank C++ solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
TheCScience
HackerRank Luck Balance Problem Solution

HackerRank Luck Balance Problem Solution

Yashwant Parihar, June 3, 2023August 1, 2024

In this post, we will solve HackerRank Luck Balance Problem Solution.

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, L[i] and T[i]:
L[i] 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].
T[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
k = 2
L = [5, 1, 4]
T= [1,1,0]

Contest		L[i]	T[i]
1		5	1
2		1	1
3		4	0

If Lena loses all of the contests, her will be 5+1+4 = 10. Since she is allowed to lose 2 important contests, and there are only 2 important contests, she can lose all three contests to maximize her luck at 10.
If k = 1, she has to win at least 1 of the 2 important contests. She would choose to win the lowest value important contest worth 1. Her final luck will be 5+ 4-1 = 8.
Function Description
Complete the luckBalance function in the editor below.
luckBalance has the following parameter(s):
int k: the number of important contests Lena can lose
int contests[n][2]: a 2D array of integers where each contests[i] contains two integers that represent the luck balance and importance of the ¿th contest
Returns

  • int: the maximum luck balance achievable

Input Format

The first line contains two space-separated integers n and k, the number of preliminary contests and the maximum number of important contests Lena can lose.
Each of the next n lines contains two space-separated integers, L[i] and T[i], the contest’s luck balance and its importance rating.

ample Input

STDIN       Function
-----       --------
6 3         n = 6, k = 3
5 1         contests = [[5, 1], [2, 1], [1, 1], [8, 1], [10, 0], [5, 0]]
2 1
1 1
8 1
10 0
5 0

Sample Output

29

Explanation
There are n = 6 contests. Of these contests, 4 are important and she cannot lose more thank = 3 of them. Lena maximizes her luck if she wins the 3rd important contest (where Li]= 1) and loses all of the other five contests for a total luck balance of 5+2+8+10+5-1=29.

HackerRank Luck Balance Problem Solution
HackerRank Luck Balance Problem Solution

Luck Balance C Solution

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int cmp(const void *a,const void *b)
    {
    return *(int *)b-*(int *)a;
}
int main() {

    int n,k,i,j=0,m=0,c;
    
    long int sum=0;
    long int b,sum1=0;
    scanf("%d%d",&n,&k);
    int a[n+1];
    for(i=0;i<n;i++)
        {
        scanf("%ld%d",&b,&c);
        if(c==1)
            {
            a[j++]=b;
            sum1+=b;
        }
        else if(c==0)
            sum1+=b;
    }
   
    if(j>=1)
    qsort(a,j,sizeof(int),cmp);
    for(i=k;i<j;i++)
        sum1-=(2*a[i]);
    printf("%ld\n",sum1);
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */    
    return 0;
}

Luck Balance C++ Solution

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int n, k, l, t;
    cin >> n >> k;
    vector<int> important;
    int ans = 0;
    for (int i = 0; i < n; ++i) {
        cin >> l >> t;
        ans += (1 - t) * l;
        if (t) {
            important.push_back(l);   
        }
    }
    sort(important.begin(), important.end());
    for (int i = 0; i < (int) important.size(); ++i) {
        int coef = -1;
        if ((int)important.size() - i <= k) coef *= coef;
        ans += important[i] * coef;
    }
    cout << ans << endl;
    return 0;
}

Luck Balance C++ Solution

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
    static void Main(String[] args) {
        string[] paramters = Console.ReadLine().Split(' ');
        int N = Convert.ToInt32(paramters[0]);
        int K = Convert.ToInt32(paramters[1]);
        List<Contest> importantContests = new List<Contest>();
        List<Contest> unimportantContests = new List<Contest>();
        for (int i = 0; i < N; i++)
        {
            string input = Console.ReadLine();
            var contest = new Contest(input);
            if (contest.Important)
            {
                importantContests.Add(contest);
            }
            else
            {
                unimportantContests.Add(contest);
            }
        }

        if (importantContests.Count < K)
        {
            Console.WriteLine(importantContests.Sum(x => x.Luck) + unimportantContests.Sum(x => x.Luck));
        }
        else
        {
            var orderedImportantContests = importantContests.OrderByDescending(x => x.Luck);
            int luckGained = orderedImportantContests.Take(K).Sum(x => x.Luck) + unimportantContests.Sum(x => x.Luck);
            int luckLost = orderedImportantContests.Skip(K).Take(importantContests.Count - K).Sum(x => x.Luck);
            Console.WriteLine(luckGained - luckLost);
        }
    }
}

public class Contest
{
    public int Luck { get; set; }
    public bool Important { get; set; }

    public Contest(string input)
    {
        string[] values = input.Split(' ');
        this.Luck = Convert.ToInt32(values[0]);
        this.Important = Convert.ToInt32(values[1]) == 1;
    }
}

Luck Balance Java Solution

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Solution {

    public static void main(String args[]) {
    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    int k=sc.nextInt();
    int values[]=new int[n];
    int imp[]=new int[n];
    int l=-1,m=-1;
    for(int i=0;i<n*2;i++){
        if(i%2!=0)
        imp[++l]=sc.nextInt();
        else
        values[++m]=sc.nextInt();
    }
    for(int i=0;i<n-1;i++)
    for(int j=i+1;j<n;j++){
        if(values[j]>values[i]){
            int temp=values[i];
            int temp2=imp[i];
            values[i]=values[j];
            values[j]=temp;
            imp[i]=imp[j];
            imp[j]=temp2;
        }
    }
    int Result=0;
    for(int i=0;i<n;i++){
        if(imp[i]==1&&k>0){
            Result+=values[i];
            k--;
        }
        else if(imp[i]==1&&k==0)
        Result-=values[i];
        else
        Result+=values[i];
    }
    System.out.println(Result);
    }
}

Luck Balance JavaScript Solution

function processData(input) {
    //Enter your code here 
    var inputAsLines = input.split('\n');
    var N = parseInt(inputAsLines[0].split(' ')[0]);
    var K = parseInt(inputAsLines[0].split(' ')[1]);
    var runningTotal = 0;
    var impArray = new Array();
    
    for(var i=0;i<N;i++) {
        var line = inputAsLines[i+1].split(' ');
        var Li = parseInt(line[0]);
        var Ti = parseInt(line[1]);
        
        runningTotal+=Li;
        
        if (Ti==1)
            impArray.push(Li);
    }
    
    impArray.sort(function(a, b) {
      return a - b;
    });

    var outputArray = impArray.slice(0,impArray.length - K);
    var output = outputArray.reduce(function(pv, cv) { return pv + cv; }, 0);
    if (K>=impArray.length) {
        console.log(runningTotal);
    }
    else
        {
    console.log(runningTotal - output*2);        
        }
    
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

Luck Balance Python Solution

n, k = input().strip().split()
n, k = int(n), int(k)

totalLuck = 0
importantLucks = []
importantLuckCount = 0

for i in range(n):
    li, ti = input().strip().split()
    if ti == "0":
        totalLuck += int(li)
    else:
        importantLucks.append(int(li))
        importantLuckCount += 1

importantLucks = sorted(importantLucks, reverse = True)

while importantLuckCount > k:
    totalLuck -= importantLucks[importantLuckCount-1]
    importantLucks = importantLucks[: (importantLuckCount-1)]
    importantLuckCount -= 1

for l in importantLucks:
    totalLuck += l

print(totalLuck)
c C# C++ HackerRank Solutions java javascript python CcppCSharpHackerrank Solutionsjavajavascriptpython

Post navigation

Previous post
Next post
  • HackerRank Dynamic Array Problem Solution
  • HackerRank 2D Array – DS Problem Solution
  • Hackerrank Array – DS Problem Solution
  • Von Neumann and Harvard Machine Architecture
  • Development of Computers
©2025 TheCScience | WordPress Theme by SuperbThemes