LeetCode 1464. Maximum Product of Two Elements in an Array
考点 | 难度 |
---|---|
Sorting | Easy |
题目
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)
.
思路
遍历nums
,分别和max1
和max2
比较。
如果大于max1
:当前的max1
和max2
替换,max1
改为新值
如果不大于max1
,大于max2
:max2
改为新值
答案
public int maxProduct(int[] nums) {
int max1 = 0;
int max2 = 0;
for(int i:nums){
if(i>max1){
max2 = max1;
max1 = i;
}
else if(i>max2){
max2 = i;
}
}
return (max1-1)*(max2-1);
}