0

I am trying to get the key that has maximum value in the map which I have created through new Map() and added the keys & values in it.

Now, I wanted to get the key whose value is maximum and if two keys have the same values then I want to return the lexicographically largest.

For eg: {'a': 20, 'b':20} then I want b to be return.

my code:

var slowestKey = function(releaseTimes, keysPressed) {
    let map=new Map();
     map.set(keysPressed[0],releaseTimes[0]);  
    for(let i=0; i<releaseTimes.length-1; i++){
         let time=releaseTimes[i+1]-releaseTimes[i];
            map.set(keysPressed[i+1],time);
    }
    let max= Math.max(...map.values());
    console.log(map)
    console.log(Math.max(...map.values()));
    
};

Input:

Input: releaseTimes = [9,29,49,50], keysPressed = "cbcd"

Expected Output: "c"

console.log:

Map(3) { 'c' => 20, 'b' => 20, 'd' => 1 }
20

How can I get the key whose value is maximum and lexicographically bigger?

2 Answers 2

2

By having an array of key/value pairs, you could sort by

  • value descending
  • key descending

and take the first pair (index 0).

const
    pairs = [['c', 9], ['b', 29], ['c', 49], ['d', 50], ['a', 50]];

pairs.sort((a, b) => b[1] - a[1] || b[0].localeCompare(a[0]));

console.log(pairs[0]);

Sign up to request clarification or add additional context in comments.

2 Comments

And, how can I sort lexicographically in array. Like ['abc', 'bc'] to ['cba','cb'] ?
just with sort().
1

With filter you can filter the keys whose value = max value, then you can sort, and get the first item.

So, the extra code will be

const [key] = [...map.keys()].filter(key => {
      return map.get(key) === max
 }).sort((a, b) => a - b)

var slowestKey = function(releaseTimes, keysPressed) {
    let map=new Map();
     map.set(keysPressed[0],releaseTimes[0]);  
    for(let i=0; i<releaseTimes.length-1; i++){
         let time=releaseTimes[i+1]-releaseTimes[i];
            map.set(keysPressed[i+1],time);
    }
    let max= Math.max(...map.values());
    const [key] = [...map.keys()].filter(key => {
      return map.get(key) === max
    }).sort((a, b) => a - b)
    console.log(key)
};


slowestKey([9,29,49,50], "cbcd")

2 Comments

And, how can I sort lexicographically in array. Like ['abc', 'bc'] to ['cba','cb'] ?
You can use this. const arr = ['abc', 'bc']; const result = arr.map(i => i.split('').sort((a, b) => b.localeCompare(a)).join('')).sort((a, b) => b.localeCompare(a))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.