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

题目

给你一个整数数组 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);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_索伦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值