置頂

GeoGebra 文章目錄

GeoGebra 文章目錄  更新日期:2018/2/8 我將 GeoGebra 相關的文章及檔案連結都整理在這篇裡,之後如果有新的文章也會同時更新這個目錄。上傳到 GeoGebraTube 的檔案,我有試著用 Google Chrome 63.0.3239.13...

熱門文章

2026年7月27日 星期一

LeetCode 解題筆記:1464. Maximum Product of Two Elements in an Array

作者:王一哲
日期:2026年7月17日


LeetCode 題目連結:1464. Maximum Product of Two Elements in an Array

解題想法


簡單題。題目給一個陣列 $nums$,取出其中 2 個數字 $nums[i], nums[j]$,回傳 $(nums[i] - 1) \times (nums[j] - 1)$ 的最大值。由於這題的數值範圍是 $1 \leq nums[i] \leq 1000$,不需要考慮兩個負數相乘的狀況,只要用一個 for 迴圈掃過 $nums$,取出 2 個最大的數字 $a, b$,回傳 $(a-1) \times (b-1)$ 即可。

Python 程式碼


Runtime: 0 ms, beats 100.00%. Memory: 19.20 MB, beats 68.04%.
class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        a, b = -1, -1
        for num in nums:
            if num > a:
                a, b = num, a
            elif num > b:
                b = num
        return (a-1) * (b-1)


C++ 程式碼


Runtime: 0 ms, beats 100.00%. Memory: 13.51 MB, beats 25.65%.
class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int a = -1, b = -1;
        for(int num : nums) {
            if (num > a) {
                b = a; a = num;
            } else if (num > b) {
                b = num;
            }
        }
        return (a-1) * (b-1);
    }
};


C 語言程式碼


Runtime: 0 ms, beats 100.00%. Memory: 9.01 MB, beats 57.35%.
int maxProduct(int* nums, int numsSize) {
    int a = -1, b = -1;
    for(int i = 0; i < numsSize; i++) {
        int num = nums[i];
        if (num > a) {
            b = a; a = num;
        } else if (num > b) {
            b = num;
        }
    }
    return (a-1) * (b-1);
}


沒有留言:

張貼留言