-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path13 MinAvgTwoSlice
40 lines (32 loc) · 1.58 KB
/
13 MinAvgTwoSlice
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
/*------------------------------------------------
A non-empty array A consisting of N integers is given.
A pair of integers (P, Q), such that 0 ≤ P < Q < N, is called a slice of
array A (notice that the slice contains at least two elements).
The average of a slice (P, Q) is the sum of A[P] + A[P + 1] + ... + A[Q] divided by
the length of the slice. To be precise, the average equals (A[P] + A[P + 1] + ... + A[Q]) / (Q − P + 1).
The goal is to find the starting position of a slice whose average is minimal.
Write a function that, given a non-empty array A consisting of N integers,
returns the starting position of the slice with the minimal average.
If there is more than one slice with a minimal average, you should return the
smallest starting position of such a slice.
------------------------------------------------*/
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
let minimalAverage = (A[0] + A[1]) / 2;
let startingPosition = 0;
for (let i=1; i<A.length; i+=1) {
let currentDoubleAvg = (A[i] + A[i+1])/2;
let currentTripleAvg = (A[i] + A[i+1] + A[i+2])/3;
if (i+1 < A.length && currentDoubleAvg < minimalAverage) {
minimalAverage = currentDoubleAvg;
startingPosition = i;
}
if (i+2 < A.length && currentTripleAvg < minimalAverage) {
minimalAverage = currentTripleAvg;
startingPosition = i;
}
}
return startingPosition;
}