Quick actions

cmd+k|ctrl+k

Navigation

Languages

Min Cost Of Array

Snippet info

Language

JavaScript

Visibility

public

Author

soham57

Created

2022-07-19T07:42:19.91809Z

Updated

2022-07-19T07:42:19.91809Z

'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}



/*
 * Complete the 'getMinimumCost' function below.
 *
 * The function is expected to return a LONG_INTEGER.
 * The function accepts INTEGER_ARRAY arr as parameter.
 */
function sortFrequency(arr)
{
    let n = arr.length;
        let  mapCount
            = new Map();
        let  mapIndex
            = new Map();
        for (let i = 0; i < n; i++) {
            if (mapCount.has(arr[i])) {
                mapCount.set(arr[i],
                             mapCount.get(arr[i]) + 1);
            }
            else {
                mapCount.set(arr[i],1); // Map to capture Count of elements
                mapIndex.set(arr[i],i); // Map to capture 1st occurrence of elements
            }
        }
  
        arr.sort(function(n1,n2){
             
                let freq1 = mapCount.get(n1);
                let freq2 = mapCount.get(n2);
                if (freq1 != freq2) {
                    return freq2 - freq1;
                }
                else {
                    return mapIndex.get(n1)
                        - mapIndex.get(
                            n2); // Elements with Lesser
                                 // Index gets Higher
                                 // Priority
                }
             
        });
        return(arr);
}

function arrCost(arr){
    let mySet=new Set();
    let cost=0;
    for(let x of arr){
        mySet.add(x);
        cost+=mySet.size;
    }
    return cost;   
    
}

function getMinimumCost(arr) {
      
   let freqArr=sortFrequency(arr);
   //console.log(freqArr);
     
    return arrCost(freqArr);
    

}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const arrCount = parseInt(readLine().trim(), 10);

    let arr = [];

    for (let i = 0; i < arrCount; i++) {
        const arrItem = parseInt(readLine().trim(), 10);
        arr.push(arrItem);
    }

    const result = getMinimumCost(arr);

    ws.write(result + '\n');

    ws.end();
}
INFO