JSFiddle - React, Tailwind, and code Playground

by dipeshbeckham

JavaScript

/*
* Here i have declared initial input which we discussed over whatsapp which would be as below.
* For now i have added \n into string to prove the concept, and test faster.
*/
const inputString = "10 10\n2\n7\n5\n9\n6\n1\n8\n10\n3\n4";

/*
* Next two line is to split and make input appropiate for next process.
*/
let originalInputArr = inputString.split("\n");
let inputSet = originalInputArr[0].split(' ');

/*
* Set initial values for N and M. For first set.
*/
let N = inputSet[0];
let M = inputSet[1];

let resultArr = [];
const processGoodRange = (input, N) =>
{
    /* Converted input to integer as we have split them so it may take it as string, sorted it */
    resultArr.push(parseInt(input));
    resultArr.sort((a,b) => a - b);

    // console.log("N: => "+ N);
    // console.log(resultArr);

    let sum = 0;
    
    for (let i= resultArr.length-1; i>=0; i--) {
        sum += parseInt(resultArr[i-1] ? resultArr[i-1] + 1 : 1)  + parseInt( resultArr[i+1] ? resultArr[i+1] - 1 : N);
    }

    console.log(sum);
}

for (let i = 1; i < originalInputArr.length; i++) {
    processGoodRange(originalInputArr[i], N)
}