Skip to content

Instantly share code, notes, and snippets.

@allenhwkim
Created July 4, 2022 00:02
Show Gist options
  • Save allenhwkim/16b9f461a59c6f8d57e1fda751f0b5b8 to your computer and use it in GitHub Desktop.
Save allenhwkim/16b9f461a59c6f8d57e1fda751f0b5b8 to your computer and use it in GitHub Desktop.
/**
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.
For example, given array A such that:
A[0] = 4
A[1] = 2
A[2] = 2
A[3] = 5
A[4] = 1
A[5] = 5
A[6] = 8
the function should return 1, as explained above.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [2..100,000];
each element of array A is an integer within the range [−10,000..10,000].
*/
function solution(A) {
console.log({A})
let ndx = 0;
let min = Number.MAX_VALUE;
// find min. index for slice of two
for (var i=0; i<A.length -1; i++) {
const avg = (A[i] + A[i+1]) / 2;
if (avg < min) {
min = avg;
ndx = i;
console.log({avg, min, i})
}
}
// find min. index for slice of three
for (var i=0; i<A.length -2; i++) {
const avg = (A[i] + A[i+1] + A[i+2]) / 3;
if (avg < min) {
min = avg;
ndx = i;
console.log({avg, min, i})
}
}
console.log({ndx})
return ndx;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment