LeetCode Problem - Link

Problem

Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.

 

Example 1:

Input: nums = [3,2,1]
Output: 1
Explanation:
The first distinct maximum is 3.
The second distinct maximum is 2.
The third distinct maximum is 1.

Sequential Approach [No Smarty business solution]

/**
 * @param {number[]} nums
 * @return {number}
 */
var thirdMax = function (nums) {


    const nth_max = 3 // constant variable that can be declared to return nth max number
    // map to remove duplicates
    var map = {}
    nums.map((num, index) => {
        if (map[num]) {
            map[num] += 1
        } else {
            map[num] = 1
        }
    })
    let keys = (Object.keys(map))
    let new_arr = []


    // get a unique array
    for (var i = 0; i < keys.length; i++) {
        new_arr.push(parseInt(keys[i])) // convert to int
    }


    // sort the unique array (purists will hate me for this, but i got lazy)
    new_arr.sort((a, b) => { return a - b })


    // return based on the logic
    if (new_arr.length < nth_max) {
        return new_arr[new_arr.length - 1]
    }


    return new_arr[new_arr.length - nth_max]


};