Header Ad

HackerRank Luck Balance Interview preparation kit problem solution

In this HackerRank Luck Balance interview preparation kit problem you need to complete the luckBalance function in the editor.


HackerRank Luck Balance Interview preparation kit solution


Problem solution in Python programming.

N, K = map(int, input().strip().split())

luck = 0
important = []

for i in range(N):
    L, T = list(map(int, input().strip().split()))
    if T == 0:
        luck += L
    else:
        important.append(L)
        
for i in sorted(important, reverse=True):
    if K > 0:
        luck += i
        K -= 1
    else:
        luck -= i

print(luck)



Problem solution in Java Programming.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the luckBalance function below.
   static int luckBalance(int k, int[][] c) {
        PriorityQueue<Integer> imp = new PriorityQueue<>(Collections.reverseOrder());
        int luck = 0;
        for(int row = 0; row < c.length; row++){
            if(c[row][1] == 0) luck += c[row][0]; else imp.offer(c[row][0]);
        }
        boolean decreaseLuck = false;
        while(!imp.isEmpty()){
            if(k == 0) decreaseLuck = true;
            if(decreaseLuck == true) luck -= imp.poll(); else luck += imp.poll();
            k--;
        }return luck;   
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String[] nk = scanner.nextLine().split(" ");

        int n = Integer.parseInt(nk[0]);

        int k = Integer.parseInt(nk[1]);

        int[][] contests = new int[n][2];

        for (int i = 0; i < n; i++) {
            String[] contestsRowItems = scanner.nextLine().split(" ");
            scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

            for (int j = 0; j < 2; j++) {
                int contestsItem = Integer.parseInt(contestsRowItems[j]);
                contests[i][j] = contestsItem;
            }
        }

        int result = luckBalance(k, contests);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedWriter.close();

        scanner.close();
    }
}


Problem solution in C++ programming.

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <utility>
#include <cstring>
#include <bitset>
#include <string>
#include <vector>
#include <queue>
#include <map>
#include <set>
using namespace std;

typedef double db;
typedef long long LL;
typedef pair< int, int > PII;
typedef pair< LL, LL > PLL;
typedef pair< db, db > PDD;

const db dInf = 1E90;
const LL lInf = ( LL ) 1E16;
const int Inf = 0x23333333;
const int N = 505;

#define it iterator
#define rbg rbegin()
#define ren rend()
#define fdi( i, x ) for ( typeof( x.rbg ) i=x.rbg; i!=x.ren; ++i )
#define foi( i, x ) for ( typeof( x.begin() ) i=x.begin(); i!=x.end(); ++i )
#define fd( i, y, x ) for ( int i=( y )-1, LIM=x; i>=LIM; --i )
#define fo( i, x, y ) for ( int i=x, LIM=y; i<LIM; ++i )
#define mkp( A, B ) make_pair( A, B )
#define pub( x ) push_back( x )
#define pob( x ) pop_back( x )
#define puf( x ) push_front( x )
#define pof( x ) pop_front( x )
#define fi first
#define se second

void Read( int &x )
{
	x = 0; char ch = '\0';
	while ( ch<'0' || ch>'9' ) ch = getchar();
	while ( ch>='0' && ch<='9' )
		x = x * 10 + ch - '0', ch = getchar();
}

void update( int &x, int v ) { if ( v > x ) x = v; }

int f[N];
int n, m;

int main()
{

	int v, imp;
	Read( n ), Read( m );
	fill( f + 1, f + m + 1, -Inf );
	fo ( i, 0, n )
	{
		Read( v ), Read( imp );
		fd ( j, m+1, 0 ) 
		{
			int temp = f[j]; f[j] = -Inf;
			update( f[ j+imp ], temp + v );
			update( f[j], temp - v );
		}
	}
	int ret = -Inf;
	fo ( j, 0, m+1 ) update( ret, f[j] );
	printf( "%d\n", ret );

	return 0;
}


Problem solution in C programming.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int comp(void *a,void *b)
    {
    return *(int *)b-*(int *)a;
}

int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
    int n,k;
    scanf("%d %d",&n,&k);
    int i,temp,flag;
    int a[n],c=0;
    long long int sum=0;
    for(i=0;i<n;i++)
        {
        scanf("%d %d",&temp,&flag);
        if(flag==0)
            sum+=temp;
        else
            {
            a[c++]=temp;
        }
    }
    qsort(a,c,sizeof(temp),(void *)comp);
    for(i=0;i<c;i++)
    {
        if(i<k)
            sum+=a[i];
        else
            sum-=a[i];
    }
    printf("%lld\n",sum);
    return 0;
}


Problem solution in JavaScript programming.

function processData(input) {
    //Enter your code here
    var lines = input.split("\n");
    var NK = lines[0].split(" ").map(Number);
    var n = NK[0];
    var k = NK[1];
    var luck=0;
    var impo=[];
    
    for (var i=0; i < n ; i++) {
        var LI = lines[i+1].split(" ").map(Number);        
        if (LI[1]==0) {
            luck += LI[0];
            //console.log("unimport => lose " + LI[0]);
        } else {
            impo.push(LI[0]);
            //console.log("important => wait " + LI[0]);
        }
    }
    impo.sort(function(a,b) { return b - a;});
    //console.log(impo);
    for (var i=0 ; i < impo.length ; i++) {
        if (i < k) {
            luck += impo[i];            
        } else {
            luck -= impo[i];
        }
    }
    
    console.log(luck);
} 

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

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


Post a Comment

0 Comments