忽略的网站,天猫网站设计,企业建站划算吗,房价开始下跌最新消息题目
给定一个数组#xff0c;找出数组中乘积最大的三个数。
原理
一个数组中最大值只有两种情况#xff1a;两个最小的负数和一个最大的正数 三个最大的正数。线性扫描找出这五个数字#xff0c;即可求出最大值。
代码 public static void main(String[] args) {…题目
给定一个数组找出数组中乘积最大的三个数。
原理
一个数组中最大值只有两种情况两个最小的负数和一个最大的正数 三个最大的正数。线性扫描找出这五个数字即可求出最大值。
代码 public static void main(String[] args) {System.out.println(getMax(new int[]{-2, -3, -4, 1, 3, 2}));}private static int getMax(int[] arr) {int min1 Integer.MAX_VALUE, min2 Integer.MAX_VALUE;int max1 Integer.MIN_VALUE, max2 Integer.MIN_VALUE, max3 Integer.MIN_VALUE;for (int n : arr) {if (n min1) {min2 min1;min1 n;} else if (n min2) {min2 n;} else if (n max1) {max3 max2;max2 max1;max1 n;} else if (n max2) {max3 max2;max2 n;} else if (n max3) {max3 n;}}return Math.max(min1 * min2 * max1, max1 * max2 * max3);}