LeetCode 1464. Maximum Product of Two Elements in an Array

Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).

Example 1:

Input: nums = [3,4,5,2]
Output: 12 
Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. 

Example 2:

Input: nums = [1,5,4,5]
Output: 16
Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.

Example 3:

Input: nums = [3,7]
Output: 12

Constraints:

  • 2 <= nums.length <= 500
  • 1 <= nums[i] <= 10^3

求一个数组中挑两个数字,两个数字分别-1后的乘积最大。和之前做过的628很像(LeetCode 628. Maximum Product of Three Numbers_wenyq7的博客-CSDN博客),最大的乘积要么是最大的两个相乘,要么是最小的两个相乘。可以先sort一下再取,也可以直接一遍O(n)找最大最小。这题还写了nums[i]都是正数,其实可以直接无脑最大的两个相乘,但不general。

sort:

class Solution {
    public int maxProduct(int[] nums) {
        int len = nums.length;
        Arrays.sort(nums);
        return Math.max((nums[len - 1] - 1) * (nums[len - 2] - 1), (nums[0] - 1) * (nums[1] - 1));
    }
}

O(n): 微微小坑,当要更新最大和最小值时,别忘了把第二大和第二小的值update成原先的最大/最小值。

class Solution {
    public int maxProduct(int[] nums) {
        int max = Integer.MIN_VALUE;
        int max2 = Integer.MIN_VALUE;
        int min = Integer.MAX_VALUE;
        int min2 = Integer.MAX_VALUE;
        for (int i : nums) {
            if (i > max) {
                max2 = max;
                max = i;
            } else if (i > max2) {
                max2 = i;
            }
            if (i < min) {
                min2 = min;
                min = i;
            } else if (i < min2) {
                min2 = i;
            }
        }
        return Math.max((min - 1) * (min2 - 1), (max - 1) * (max2 - 1));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值