I am trying to solve a Leetcode problem with JavaScript
#643 Maximum Average Subarray
My solution works for all the test cases but the time complexity is too high. How can I optimize this?
var findMaxAverage = function(nums, k) {
let maxsum = undefined;
let sum = 0;
for(let j=0; j<=nums.length-k;j++){
for(let i = j; i<j+k; i++){
sum+=nums[i]
}
if(maxsum <= sum || maxsum == undefined){
maxsum = sum;
}
sum=0;
}
return maxsum/k;
Also I want to understand how to calculate the time complexity im guessing its O( (n-k+1) * k) please help me with this as well.
Thank you