Sherlock and MiniMax Discussions | Algorithms | HackerRank

Sherlock and MiniMax

  • + 0 comments
    function sherlockAndMinimax(arr, p, q) {
        // Write your code here
        let maxInd = p;
        let minimum = Number.MAX_SAFE_INTEGER;
        arr.sort((a, b) => a - b);
        
        for (const element of arr) {
            const absP = Math.abs(element - p);
            if (absP < minimum) {
                minimum = absP;
            }
        }
        let maximum = minimum;
        minimum = Number.MAX_SAFE_INTEGER;
        
        for (let i = 1; i <= arr.length; i++) {
            const mid = parseInt((arr[i] + arr[i - 1]) / 2, 10);
            if (p < mid && mid < q) {
                minimum = Math.min(mid - arr[i - 1], arr[i] - mid);
                if (minimum > maximum) {
                    maximum = minimum;
                    maxInd = mid;
                }
            }
        }
        
        minimum = Number.MAX_SAFE_INTEGER;
        for (const element of arr) {
            const absQ = Math.abs(element - q);
            if (absQ < minimum) {
                minimum = absQ;
            }
        }
        
        if (minimum > maximum) {
            maximum = minimum;
            maxInd = q;
        }
    
        return maxInd;
    }