LeetCode1464.数组中两元素的最大乘积

这篇博客探讨了如何在给定整数数组中找到两个元素,使得它们相减一后的乘积最大。提供了两种解题思路:一是遍历数组,二是先对数组排序。在示例中,给定数组[3, 4, 5, 2],通过遍历或排序方法,可以得出最大乘积为12。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

给你一个整数数组 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);
}