↓快轉到主要內容
  1. LeetCode/

LeetCode 3536: Maximum Product of Two Digits

·1 分鐘· ·
LeetCode Easy Math Sorting
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2025-05-04

  • 提交紀錄:Runtime Error ×4 → Wrong Answer ×2 → Accepted

解題思路
#

答案是最大的兩個位數相乘(同一個數字出現兩次可以用兩次)。最簡單是把位數排序取最後兩個;一次掃描的話,維護 max1 >= max2:

  • 新的位數 > max1:舊的 max1 變成 max2,新的變成 max1。
  • 否則如果 > max2:更新 max2。

我的嘗試
#

版本問題
四次 REmap(n, str) 參數順序反了;接著是字串跟整數 0 比較、字串相乘等型別錯誤
兩次 WA型別修好了,但找到新的最大值時,舊的最大值沒有移到第二名。例如 n = 789:答案是 9 × 8 = 72,兩版都回傳 0。第一版的條件是 >=,相同的 7 也只會蓋掉第一名,所以 n = 707 回傳 0,答案是 49
AC改成 max1, max2 = s, max1

正確解法
#

class Solution:
    def maxProduct(self, n: int) -> int:
        digits = sorted(int(c) for c in str(n))
        return digits[-1] * digits[-2]

複雜度
#

時間 O(d log d),d 是位數(最多 10 位),空間 O(d)。

要特別避免的錯誤
#

  • 字串和整數混著比較。
  • 維護前兩名時,新的第一名出現,舊的第一名要變成第二名。

面試口說整理
#

答案是最大的兩個位數相乘。我把位數排序取最後兩個;如果要一次掃描,就維護第一名和第二名,新的第一名出現時舊的第一名降成第二名。時間 O(d)。

相關文章

LeetCode 1030: Matrix Cells in Distance Order
·1 分鐘
LeetCode Easy Array Math Geometry Sorting
LeetCode 1030 解題筆記:列出所有座標,按到中心的曼哈頓距離排序;回傳的是座標,不是距離
LeetCode 628: Maximum Product of Three Numbers
·1 分鐘
LeetCode Easy Array Math Sorting
LeetCode 628 解題筆記:排序後答案只有兩種可能:最大的三個相乘,或最小的兩個(負數)乘最大的一個
LeetCode 3492: Maximum Containers on a Ship
·1 分鐘
LeetCode Easy Math
LeetCode 3492 解題筆記:最多 n² 個格子,重量最多放 maxWeight // w 個,取兩者較小值;用整數除法
LeetCode 3074: Apple Redistribution into Boxes
·1 分鐘
LeetCode Easy Array Greedy Sorting
LeetCode 3074 解題筆記:箱子可以隨便分,所以從容量最大的箱子開始拿,總容量夠裝所有蘋果就停
LeetCode 2099: Find Subsequence of Length K With the Largest Sum
·1 分鐘
LeetCode Easy Array Hash-Table Sorting Heap-Priority-Queue
LeetCode 2099 解題筆記:選出最大的 k 個數(連同 index),再按 index 排回原本的順序
LeetCode 2231: Largest Number After Digit Swaps by Parity
·1 分鐘
LeetCode Easy Sorting Heap-Priority-Queue
LeetCode 2231 解題筆記:奇數位數只能跟奇數交換、偶數只能跟偶數交換;分別排序後,依原本每個位置的奇偶放回最大的