LeetCode 1464. 数组中两元素的最大乘积
给你一个整数数组 nums,请你选择数组的两个不同下标 i 和 j,使 (nums[i]-1)*(nums[j]-1) 取得最大值。
请你计算并返回该式的最大值。
2 <= nums.length <= 500
1 <= nums[i] <= 10^3
遍历找出数组中的最大值和次最大值即可:
class Solution {
public:
int maxProduct(vector<int>& nums) {
int i = 0, j = 0; // i是最大值,j是次大值
for (int num : nums) {
if (num > i) {
j = i; // 当前最大值变为次大值
i = num;
} else if (num > j) {
j = num;
}
}
return (i - 1) * (j - 1);
}
};
还没有评论,来说两句吧...