LeetCode C++ 1464. Maximum Product of Two Elements in an Array【Array/Sort】簡單

memcpy0發表於2020-11-13

Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i] - 1) * (nums[j] - 1) .

Example 1:

Input: nums = [3,4,5,2]
Output: 12 
Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. 

Example 2:

Input: nums = [1,5,4,5]
Output: 16
Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.

Example 3:

Input: nums = [3,7]
Output: 12

Constraints:

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

題意:給定一個整數陣列 nums,選擇陣列的兩個不同下標 ij ,使 (nums[i] - 1) * (nums[j] - 1) 取得最大值並返回。


解法1 暴力

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int mv = 0, n = nums.size();
        for (int i = 0; i < n; ++i) 
            for (int j = i + 1; j < n; ++j) 
                mv = max(mv, (nums[i] - 1) * (nums[j] - 1));
        return mv;
    }
};

執行效率很低:

執行用時:60 ms, 在所有 C++ 提交中擊敗了6.69% 的使用者
記憶體消耗:10.2 MB, 在所有 C++ 提交中擊敗了13.32% 的使用者

解法2 排序

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        sort(nums.begin(), nums.end(), greater<int>());
        return (nums[0] - 1) * (nums[1] - 1);
    }
};

執行效率如下:

執行用時:8 ms, 在所有 C++ 提交中擊敗了94.49% 的使用者
記憶體消耗:10 MB, 在所有 C++ 提交中擊敗了33.58% 的使用者

解法3 線性比較

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int max = 0, sec = 0, n = nums.size();
        for (int i = 0; i < n; ++i) {
            if (nums[i] > max) sec = max, max = nums[i];
            else if (nums[i] > sec) sec = nums[i];
        }  
        return (max - 1) * (sec - 1);
    }
};

執行效率如下:

執行用時:4 ms, 在所有 C++ 提交中擊敗了99.53% 的使用者
記憶體消耗:10.2 MB, 在所有 C++ 提交中擊敗了12.91% 的使用者

相關文章