Uahnbu Tran Uahnbu Tran - 5 months ago 23
Javascript Question

My code for Hackerrank challenge Service Lane doesn't work

I'm doing a challenge in www.hackerrank.com named Service Lane at https://www.hackerrank.com/challenges/service-lane. I have checked my code very carefully but it's still wrong in some cases. Here is my code: (in Javascript)

function main() {
var n_temp = readLine().split(' '), i, s;
width = readLine().split(' ');
for(var a0 = 0; a0 < n_temp[1]; a0++){
var i_temp = readLine().split(' '); s = 3;
for (i=i_temp[0];i<=i_temp[1];i++) {s = Math.min(s,width[i]); if (s == 1) break;}
console.log(s);
}
}


The challenge has a list of numbers (stored in width, their values are between 1 and 3) and some test cases (include a starting number: i_temp[0] and an ending number: i_temp[1.], both of which are inclusive). The mission is to get the smallest number in the elements from i_temp[0] to i_temp[1.] of width.
Here is one of the cases that don't work:
Input
Output
What is wrong with the code? It works successfully in some cases. Thanks for your help :D

Answer

Try this:

function main() {
    var N, n, path, i, j, it, res;
    [N, n] = readLine().split(' ').map(Number);
    var path = readLine().split(' ').map(Number);
    for (var it = 0; it < n; it++) {
      [i, j] = readLine().split(' ').map(Number);
      res = Math.min.apply(null, path.slice(i, j+1));
      console.log(res);
    }
}
Comments