子数组最大平均数

给一个整数数组,找出平均数最大且长度为k的下标连续的子数组,并输出最大平均数

输入:[1,12,-5,-6,50,3],k=4
输出:12.75
最大平均数 (12-5-6+50)/4=51/4=12.75

public class MaxProduct {
    public static void main(String[] args) {
        System.out.println(sort(new int[]{-1,-2,-3,-4,-5,-6}));
        System.out.println(getMaxMin(new int[]{1,2,3,4,5,6}));
    }
    public static int sort(int[] nums){
        Arrays.sort(nums);//从小到大排序
        int n = nums.length;
        return Math.max(nums[0]*nums[1]*nums[n-1],nums[n-1]*nums[n-2]*nums[n-3]);
    }
    //线性扫描
    public static int getMaxMin(int[] nums){
        int min1 = Integer.MAX_VALUE,min2 = Integer.MAX_VALUE;
        int max1 = Integer.MIN_VALUE,max2 = Integer.MIN_VALUE,max3 = Integer.MIN_VALUE;

        for (int x:nums){
            if (x<min1){
                min2 = min1;
                min1 = x;
            }else if (x < min2){
                min2 = x;
            }
            if (x>max1){
                max3=max2;
                max2=max1;
                max1=x;
            }else if (x>max2){
                max3=max2;
                max2=x;
            }if (x>max1){
                max3=x;
            }
        }
        return Math.max(min1*min2*max1,max1*max2*max3);
    }
}
posted @ 2021-07-29 14:05  落笔生花  阅读(120)  评论(0)    收藏  举报