Here is another codility problem solution from the codility lessons (MinAvgTwoSlice-Find the minimal average of any slice containing at least two elements.) due to the copy rights I can't copy the content of the problem here so to view the problem description click here.
class Solution {
public int solution(int[] A) {
long min = Long.MAX_VALUE;
int index = -1;
//we have A+B/2 to be comapred with A+B+C/3
//to make things easiler we are going to multuply both side with 6
for (int i = 0; i < A.length - 2; i++) {
long res1 = ((A[i] + A[i + 1])) * 3;
long res2 = ((A[i] + A[i + 1] + A[i + 2])) * 2;
long minRes = Math.min(res1, res2);
if (minRes < min) {
min = minRes;
index = i;
}
}
if ((A[A.length - 2] + A[A.length - 1]) * 3 < min) {
return A.length - 2;
}
return index;
}
}
No comments:
Post a Comment