zoukankan      html  css  js  c++  java
  • 628. 三个数的最大乘积『简单』

    题目来源于力扣(LeetCode

    一、题目

    628. 三个数的最大乘积

    提示:

    • 给定的整型数组长度范围是[3,104],数组中所有的元素范围是[-1000, 1000]。
    • 输入的数组中任意三个数的乘积不会超出32位有符号整数的范围。

    二、解题思路

    2.1 Sort排序方式

    1. 调用 Arrays.sort 排序后,得到有序的 nums 数组

    2. 直接取左侧的两个元素与最后一个元素,得到一个乘积

    3. 右侧的三个元素,得到一个乘积

    4. 返回两个乘积中的最大值

    2.2 遍历数组找最大最小值

    1. 遍历数组,手动找到三个最大值与两个最小的值

    2. 返回两个乘积中的最大值

    三、代码实现

    3.1 Sort排序方式

    public int maximumProduct(int[] nums) {
        Arrays.sort(nums);
        int len = nums.length - 1;
        // 最大乘积的两种情况
        // 两个负数和一个最大的正数乘积
        int negativeProduct = nums[0] * nums[1] * nums[len];
        // 三个较大正数的乘积
        int positiveProduct = nums[len] * nums[len - 1] * nums[len - 2];
    
        return Math.max(negativeProduct, positiveProduct);
    }
    

    3.2 遍历数组找最大最小值

    public static int maximumProduct(int[] nums) {
        // 定义变量记录最大的三个数
        int max1 = Integer.MIN_VALUE;  // 最大
        int max2 = max1;  // 第二大
        int max3 = max1;  // 第三大
    
        // 定义变量记录最小的两个数
        int min1 = Integer.MAX_VALUE;  // 最小
        int min2 = min1;  // 第二小
    
        // 遍历数组,找到最大的三个数和最小的两个数
        for (int i : nums) {
            if (i > max1) {
                // 大于最大值时
                max3 = max2;
                max2 = max1;
                max1 = i;
            } else if (i > max2) {
                // 小于最大值,大于第二大值时
                max3 = max2;
                max2 = i;
            } else if (i > max3) {
                // 小于最大值、第二大值,大于第三大值时
                max3 = i;
            }
            if (i < min1) {
                // 小于最小值时
                min2 = min1;
                min1 = i;
            } else if (i < min2) {
                // 大于最小值,小于第二小值时
                min2 = i;
            }
        }
    
        // 最大乘积的两种情况
        // 两个负数和一个最大的正数乘积
        int negativeProduct = min1 * min2 * max1;
        // 三个较大正数的乘积
        int positiveProduct = max1 * max2 * max3;
        return Math.max(negativeProduct, positiveProduct);
    }
    

    四、执行用时

    4.1 Sort排序方式

    4.2 遍历数组找最大最小值

    五、部分测试用例

    public static void main(String[] args) {
        int[] nums = {1, 2, 3};  // output:6
    //    int[] nums = {1, 2, 3, 4};  // output:24
    
        int result = maximumProduct(nums);
        System.out.println(result);
    }
    
  • 相关阅读:
    SRM 441(1-250pt, 1-500pt)
    SRM 387(1-250pt)
    SRM 388(1-250pt)
    SRM 389(1-250pt)
    SRM 601(1-250pt,500pt)
    SRM 409(1-250pt, 1-500pt)
    SRM 408(1-250pt, 1-500pt)
    unique() 去重函数
    poj3468(A Simple Problem with Integers)
    HDU1394(Minimum Inversion Number)
  • 原文地址:https://www.cnblogs.com/zhiyin1209/p/12913265.html
Copyright © 2011-2022 走看看