I made a function for finding largest subarray length. It works fine but with some input it doesn't show the correct output.
Here is my code:
function maxLength(a, k) {
function sumOfArray(arr) {
return arr.reduce((a, b) => a + b, 0);
}
var sub_array = [];
for (var i = 0; i < a.length; i++) {
for (var j = i + 1; j < a.length; j++) {
if (j - i > sub_array.length && sumOfArray(a.slice(i, j)) < k) {
sub_array = a.slice(i, j);
}
}
}
return sub_array.length;
}
console.log(maxLength([3,1,2,1,4], 4))
The input which shows wrong answer is: [3,1,2,1,4] and k = 4 which the output is 2 but the correct answer is 3
How can I fix the code
Any help will be appreciated
kdoes[3,1,2,1,4]not work?[1, 2, 1]? If so, then you need to change< kto<= k.