Codility/Lesson 5/Prefix Sums/MinAvgTwoSlice/Java

원리

  • 길이 2, 3인 대상만 검사하면 된다.

Code

// you can also use imports, for example:
import java.util.*;

// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
    public int solution(int[] A) {
        // write your code in Java SE 8
        int answer = 0;
        float minAvg = (A[0]+A[1])/2f;

        for(int i=2; i<A.length; i++) {
            float avg3 = (A[i]+A[i-1]+A[i-2])/3f;
            if(avg3 < minAvg) {
                minAvg = avg3;
                answer = i-2;
            }

            float avg2 = (A[i]+A[i-1])/2f;
            if(avg2 < minAvg) {
                minAvg = avg2;
                answer = i-1;
            }
        }

        return answer;
    }
}

result report

참고한 글

좋은 웹페이지 즐겨찾기