Hyun-soo’s father runs a bakery. Hyeon-soo’s father gave him the sales record for N days and told him to find the maximum sales for K consecutive days.
If N=10, the sales record for 10 days is as follows. In this case, if K = 3
12 15 11 20 25 10 20 19 13 15
The maximum sales for 3 consecutive days is 11+20+25=560,000 won.
Please help Hyun-soo.
10 3
12 15 11 20 25 10 20 19 13 15
Print the maximum sales on the first line.
56
function solution(k, arr) {
let answer = 0,
index = k - 1;
while (index < arr.length) {
if (arr[index - 2] + arr[index - 1] + arr[index] > answer) {
answer = arr[index - 2] + arr[index - 1] + arr[index];
}
index++;
}
return answer;
}
function solution(k, arr) {
let answer,
sum = 0;
for (let i = 0; i < k; i++) sum += arr[i];
answer = sum;
for (let i = k; i < arr.length; i++) {
sum += arr[i] - arr[i - k];
answer = Math.max(answer, sum);
}
return answer;
}