3.3 MinAvgTwoSlice

求數組最小平均數子序列起始位置
A non-empty zero-indexed 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).
For example, 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
contains the following example slices:
slice (1, 2), whose average is (2 + 2) / 2 = 2;
slice (3, 4), whose average is (5 + 1) / 2 = 3;
slice (1, 4), whose average is (2 + 2 + 5 + 1) / 4 = 2.5.
The goal is to find the starting position of a slice whose average is minimal.

Solution

double min2 = (A[0]+A[1])/2.0;
        double min3 = 10001;
        int start2 = 0;
        int start3 = 0;
        for(int i=2; i<A.length; i++){
            if((A[i-1]+A[i])/2.0 < min2){
                min2 = (A[i-1]+A[i])/2.0;
                start2 = i-1;
            }    
        }
        for(int i=2; i<A.length; i++){
            if((A[i-2]+A[i-1]+A[i])/3.0<min3){
                min3 = (A[i-2]+A[i-1]+A[i])/3.0;
                start3 = i-2;
            }
        }
        if(min2<min3) return start2;
        else return start3;

由於double的精度,導致-1,1之間時結果錯誤。最小平均子序列都可以分割爲m個兩個元素子串 和n個三子串。反證法可以證明這些子串的平均值均相等。那麼起始位置必然是兩子串或三子串的頭,窮舉所有兩子串和三子串平均值,其中最小的串即爲最小平均數子串的頭。
如果求最小平均子串的尾,利用所有子串平均值均相等性質找到尾。不建議使用presum,presum可能溢出,如果使用double也存在精度問題

点赞