题目
给你一个整数数组 nums,请你选择数组的两个不同下标 i 和 j,使 (nums[i]-1)*(nums[j]-1) 取得最大值。
请你计算并返回该式的最大值。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-of-two-elements-in-an-array
示例
输入:nums = [3,4,5,2]
输出:12
解释:如果选择下标 i=1 和 j=2(下标从 0 开始),则可以获得最大值,(nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12 。
解题思路1:遍历
本人比较笨,所以采用直接遍历一遍求解。
将nums[0]和nums[1]先赋给最大数和第二大数,遍历一遍,顺位更新。
代码
int maxProduct(int* nums, int numsSize)
{
int max = nums[0];
int nextmax = nums[1];
for (int i = 1; i < numsSize; ++i)
{
//遇到比最大值大的我,顺位更新
if (nums[i] > max)
{
nextmax = max;
max = nums[i];
}
else if (nums[i] == max) //遇到比第二大数大的,更新第二大数
{
nextmax = nums[i];
}
else if (nums[i] > nextmax && nums[i] < max)
{
nextmax = nums[i];
}
}
return (max - 1) * (nextmax - 1);
}
解题思路2:排序后取数组最后两个值
int mycmp(const void* p1, const void* p2)
{
const int* a1 = (const int*)p1;
const int* a2 = (const int*)p2;
return (*a1 > *a2) - (*a1 < *a2);
}
int maxProduct(int* nums, int numsSize)
{
qsort(nums, numsSize, sizeof(int), mycmp);
return (nums[numsSize - 2] - 1) * (nums[numsSize - 1] - 1);
}