Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Learn More

Luck Balance | Solution using C | HackerRank

3 min read



Statement


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  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,2,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+4+1 = 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  contains two integers that represent the luck balance and importance of the ith contest

Returns

  • int: the maximum luck balance achievable


Solution in C:


cpp
/* * Complete the 'luckBalance' function below. * * The function is expected to return an INTEGER. * The function accepts following parameters: * 1. INTEGER k * 2. 2D_INTEGER_ARRAY contests */ int compare(const void *a, const void *b){ return (*(int*)b-*(int*)a); } int luckBalance(int k, int contests_rows, int contests_columns, int** contests) { int imp_contest[100]; int imp_contest_length = 0; int luckBalance = 0; for (int i=0; i<contests_rows; i++) { if(contests[i][1]==1){ imp_contest[imp_contest_length]=contests[i][0]; imp_contest_length++; } else { luckBalance+=contests[i][0]; } } qsort(imp_contest, imp_contest_length, sizeof(int), compare); printf("%d %d\n",k,imp_contest_length); int n = (k<imp_contest_length)?k:imp_contest_length; printf("%d",n); for (int i=0; i<n; i++) { luckBalance += imp_contest[i]; } for (int i=k; i<imp_contest_length; i++) { luckBalance-=imp_contest[i]; } return luckBalance; } //Solution End here. Driver code starts below ;)


Labels : #array in c ,#c program ,#hackerrank ,#hackerrank c ,

1 comment

  1. second ago
    Hello awesome people.
    Share your thoughts here :)