• + 0 comments

    JS - use of array-functions: filter, sort & reduce

    function luckBalance(k, contests) {
        // Write your code here
        const unimportantArr = contests.filter(c => c[1] === 0);
        const importantArr = contests.filter(c => c[1] === 1);
        // sort -> from least important to max important
        importantArr.sort((a, b) => a[0] - b[0] < 0 ? 1 : -1);
        
        // we lose all unimportant constests for max luck
        const luckU = unimportantArr.reduce((a, c) => a + c[0] , 0);
        // the least important ones (lower than k) we win, else we lose to gain luck
        const luckI = importantArr.reduce(
            (a, c, idx) => idx >= k ? a - c[0] : a + c[0], 0);
        
        return luckU + luckI;
    }