carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1464:数组中两元素的最大乘积(maximum-product-of-two-elements-in-an-array) #232

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给你一个整数数组 nums,请你选择数组的两个不同下标 i 和 j,使 (nums[i]-1)*(nums[j]-1) 取得最大值。

请你计算并返回该式的最大值。

  示例 1:

输入:nums = [3,4,5,2] 输出:12 解释:如果选择下标 i=1 和 j=2(下标从 0 开始),则可以获得最大值,(nums[1]-1)(nums[2]-1) = (4-1)(5-1) = 3*4 = 12 。

示例 2:

输入:nums = [1,5,4,5] 输出:16 解释:选择下标 i=1 和 j=3(下标从 0 开始),则可以获得最大值 (5-1)*(5-1) = 16 。

示例 3:

输入:nums = [3,7] 输出:12  

提示:

2 <= nums.length <= 500 1 <= nums[i] <= 10^3

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/maximum-product-of-two-elements-in-an-array

carloscn commented 1 year ago

问题分析

pub fn max_product(nums: Vec<i32>) -> i32
{
    if nums.is_empty() {
        return 0;
    }

    let mut max_val:i32 = i32::MIN;
    let mut sec_val:i32 = i32::MIN;

    for i in 0..nums.len() {
        if nums[i] >= max_val {
            sec_val = max_val;
            max_val = nums[i];
        } else if nums[i] < max_val &&
                  nums[i] > sec_val {
            sec_val = nums[i];
        }
    }

    return (sec_val - 1) * (max_val - 1);
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/554585 https://github.com/carloscn/structstudy/commit/f47c269a381072ea6fa970b43e8869b461ca70e4