-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
80 lines (62 loc) · 1.73 KB
/
Copy pathindex.js
File metadata and controls
80 lines (62 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
function findGoodRangeSum(lines) {
// console.log('lines\n',lines)
const allLines = lines.split("\n");
allLines.shift(); // removed blank line from first element
allLines.pop(); // removing last element which is also blank
// console.log("allLines", allLines);
const nAndMLine = allLines.shift(); // removing n-and-m line, to store only queries (M) now
console.log("allLines", allLines);
// console.log("nAndMLine", nAndMLine);
const nAndM = nAndMLine.split(" ");
const N = +nAndM[0];
const QUERY_LENGTH = nAndM[1];
validateConstraints(N,QUERY_LENGTH, allLines);
console.log("N", N);
console.log("QUERY_LENGTH", QUERY_LENGTH);
let setA = [];
let output = [];
for (let i = 0; i < QUERY_LENGTH; i++) {
setA.push(+allLines[i]); // parsing to integer
setA = setA.sort(numberComparator);
// console.log("setA parsed :: ", setA);
let sumRange = 0;
setA.forEach((_, index) => {
const minIndex = index - 1 < 0 ? 1 : setA[index - 1] + 1;
const maxIndex = index + 1 >= setA.length ? N : setA[index + 1] - 1;
// console.log("sumRange before :: ", sumRange, minIndex, maxIndex);
sumRange = sumRange + (minIndex + maxIndex);
// console.log("sumRange after :: ", sumRange);
});
output.push(sumRange);
}
// console.log("setA", setA);
console.log("output", output);
}
function validateConstraints(n,m,queries) {
const mMaxLimit = Math.pow(10,6);
if(m >= mMaxLimit){
throw new Error(`M=${m} should be <= 10^6 = ${mMaxLimit}`);
}
queries.forEach(x=>{
if(x>n){
throw new Error(`X=${x} is greater than N=${n}`);
}
});
}
function numberComparator(a, b) {
return a - b;
}
const lines = `
10 10
2
7
5
9
6
1
8
10
3
4
`;
findGoodRangeSum(lines);