After solving a problem, I came to this conclusion.
let n = 10;
let array = [
[1, 5, 3],
[4, 8, 7],
[6, 9, 1]
];
let answer = array.map((val) => new Float32Array(n).fill(val[2], val[0] - 1, val[1]));
console.log(Math.max(...answer.reduce((r, a) => a.map((b, i) => (r[i] || 0) + b), [])))
Okay, so what this does is it creates an array of n
elements with the value of the third element from the index from the range of the first value to the second value.
Indexes start from 1 here.
Like for [1, 5, 3]
, (n = 10), it creates an array of 10 elements with the value 3 from the index 1 to the index 5 and else everything is just blank or 0.
Then for [4, 8, 7]
, (n = 10), it creates an array of 10 elements with the value 7 from the index 4 to the index 8 and else, everything is just blank or 0.
Then for [6, 9, 1]
, (n = 10), it creates an array of 10 elements with the value 1 from the index 6 to the index 9 and else, everything is just blank or 0.
Now we have to sum all the matching columns and return the maximum value, which I do by
Math.max(...answer.reduce((r, a) => a.map((b, i) => (r[i] || 0) + b), []))
Everything works fine and the test cases work but the program is not at all efficent, with refrence to this problem, my code just timeouts.
I think the problem is when I sum the values. That is what is taking the most memory.
What can be an alternate method to sum the same index array values? Being it the most efficient