Luck Balance


Problem 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 ; 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.


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 ith 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.


Sample 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



Solution :



title-img


                            Solution in C :

In C :






#include<stdio.h>
 long int sort(int a[] ,int size,int k){
	
	int i,min,j,sum=0,t; 
	for(i=0;i<k;i++){
		min=i;
		
		for(j=i+1;j<size;j++){
			if(a[min]>a[j])
			min=j;
		}
		if(i!=min){
			t=a[i];
			a[i]=a[min];
			a[min]=t;
		}
		//printf("a[%d]=%d\n",i,a[i]);
	sum+=a[i];	
	}
	//printf("sum=%d\n",sum);
return sum;	
	
}
int main(){
	int n,k,i,t;
	long int l,sum1=0,sum2;
	int ar[100],arc=0;
	scanf("%d %d",&n,&k);
	for(i=0;i<n;i++){
		
		scanf("%ld %d",&l,&t);
		
		if(t==1)
		ar[arc++]=l;
		
		
		sum1+=l;
	}
	sum2=sort(ar,arc,arc-k);
	//	printf("sum1=%d\n",sum1);
	printf("%ld",(sum1- 2*(sum2)));
	
	return 0;
}
                        


                        Solution in C++ :

In  C  ++  :






#include<bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)
#define FORD(i,a,b) for(int i = (a); i >= (b); --i)
#define RI(i,n) FOR(i,1,(n))
#define REP(i,n) FOR(i,0,(n)-1)
#define mini(a,b) a=min(a,b)
#define maxi(a,b) a=max(a,b)
#define mp make_pair
#define pb push_back
#define st first
#define nd second
#define sz(w) (int) w.size()
typedef vector<int> vi;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
const int inf = 1e9 + 5;
const int nax = 1e6 + 5;



int main() {
	int n, k;
	scanf("%d%d", &n, &k);
	int ans = 0;
	vi w;
	REP(i, n) {
		int a, b;
		scanf("%d%d", &a, &b);
		if(b == 0) ans += a;
		else w.pb(a);
	}
	sort(w.rbegin(), w.rend());
	REP(i, (int) w.size()) {
		if(i < k) ans += w[i];
		else ans -= w[i];
	}
	printf("%d\n", ans);
	return 0;
}
                    


                        Solution in Java :

In  Java :






import java.util.Arrays;
import java.util.Scanner;
public class LuckBalance {

    static class Contest implements Comparable<Contest> {
        int l,t;

        @Override
        public int compareTo(Contest o) {
            if(t == o.t) {
                return (this.l - o.l);
            }else {
                return -(this.t - o.t);
            }
        }
    }
    public static void main(String[] args) {
        int N, K;
        Scanner scanner = new Scanner(System.in);
        N = scanner.nextInt();
        K = scanner.nextInt();

        int total = 0;
        int t,l;
        Contest[] contests = new Contest[N];
        int importCnt = 0;
        for (int i = 0; i < N; i++) {

            l = scanner.nextInt();
            t = scanner.nextInt();
            total += l;
            if(t == 1) {
                importCnt++;
            }
            Contest contest = new Contest();
            contest.l = l;
            contest.t = t;

            contests[i] = contest;
        }

        Arrays.sort(contests);

        int winCnt = importCnt - K;
        if(winCnt <= 0) {
            System.out.println(total);
            return;
        }

        for (int i = 0; i < winCnt; i++) {
            total -= 2 * contests[i].l;
        }
        System.out.println(total);



    }
}
                    


                        Solution in Python : 
                            
In  Python3 :






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)
                    


View More Similar Problems

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →

Unique Colors

You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti

View Solution →