题目地址:
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/
给定一个长 n n n正整数数组 A A A,取其中两个数 x x x和 y y y使得 ( x − 1 ) ( y − 1 ) (x-1)(y-1) (x−1)(y−1)最大。求这个最大乘积。
直接求最大的两个数即可。代码如下:
public class Solution {
public int maxProduct(int[] nums) {
int max1 = Integer.MIN_VALUE, max2 = Integer.MIN_VALUE;
for (int num : nums) {
if (num > max1) {
max2 = max1;
max1 = num;
} else if (num > max2) {
max2 = num;
}
}
return (max1 - 1) * (max2 - 1);
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。