• + 0 comments

    My Java solution with o(n log n) time and o(n) space:

    public static int luckBalance(int k, List<List<Integer>> contests) {
            // determine total luck balance 
            
            // get list of important contests that holds each luck val
            int luckBalance = 0;
            List<Integer> importantContests = new ArrayList<>();
            
            // add the uninmportant contests to the luck val
            for(int i = 0; i < contests.size(); i++){
                int luckVal = contests.get(i).get(0);
                int important = contests.get(i).get(1);
                if(important == 1) importantContests.add(luckVal);
                else luckBalance += luckVal;
            }
            
            //sort descending to get highest competitions added first
            Collections.sort(importantContests, Collections.reverseOrder());
            
            //for each important contest add the important vals
            for(int j = 0; j < importantContests.size(); j++){
                luckBalance += (j < k) ? importantContests.get(j) : -importantContests.get(j);
            }
            
            return luckBalance;
        }