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));
}
}