[java]Given an integer array of length m, find the maximum average value and the value of k of the k subarrays of this array

Problem Description:

Given an array, find the maximum average value and the value of k of the subarrays of k numbers in this array

problem analysis:

The sub-arrays are continuous, for example, the array is {1, 2, 7, 7, 7} with 3 consecutive 777, then the k value is 3; but when the array is {1, 2, 7, 7, 7, 8}, The maximum average value is 8 and the k value is 1

code:

public class Array6 {
    //求 第n个数开始,k个元素的 平均值
    public int avg(int[] array, int k, int n) {
        int sum = 0;
        if (k > array.length) { // 防止k值输入过大
            System.out.println(" k  is  wrong");
            return 0;
        } else {
            if (n + k <= array.length) {// 防止数组下标越界
                for (int i = n; i < n + k; i++) {
                    sum += array[i];
                }
            }
        }
        return sum / k;
    }


    // i controls the k, and  j  is to search all the array
    public void figue(int[] array) {
        int avg = 0;
        int k = 0;
        for (int i = 1; i < array.length; i++) { //k值寻找
            for (int j = 0; j < array.length; j++) {

                if (avg(array, i, j) >= avg) {// 选取最大平均数
                    avg = avg(array, i, j);
                    k = i;
                }
            }
        }
        System.out.println("最大的平均数是" + avg + "  k is " + k);
    }

    public static void main(String[] args) {
        int[] array = {11, 23, 45, 78, 66, 66,66, 84,84, 32, 41, 99,99};
        int[] array1 = {101, 23, 45, 78, 78,78, 99};
        Array6 array6 = new Array6();
        array6.figue(array1);
    }
}

discuss:

Nested for loops, the inner layer is used to traverse the array, and the outer layer is used to find the k value, using the avg(array[], k, n) method to calculate: Starting from array[n], the average number of consecutive k values

Guess you like

Origin blog.csdn.net/dw1360585641/article/details/129175001