classSolution: defmaxSum(self, nums: List[int]) -> int: ans = -1 max_val = [-inf] * 10 for v in nums: max_d = max(map(int, str(v))) ans = max(ans, v + max_val[max_d]) max_val[max_d] = max(max_val[max_d], v) return ans
[sol-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { publicintmaxSum(int[] nums) { intans= -1; varmaxVal=newint[10]; Arrays.fill(maxVal, Integer.MIN_VALUE); for (int v : nums) { intmaxD=0; for (intx= v; x > 0; x /= 10) maxD = Math.max(maxD, x % 10); ans = Math.max(ans, v + maxVal[maxD]); maxVal[maxD] = Math.max(maxVal[maxD], v); } return ans; } }
[sol-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: intmaxSum(vector<int> &nums){ int ans = -1; vector<int> max_val(10, INT_MIN); for (int v: nums) { int max_d = 0; for (int x = v; x; x /= 10) max_d = max(max_d, x % 10); ans = max(ans, v + max_val[max_d]); max_val[max_d] = max(max_val[max_d], v); } return ans; } };
[sol-Go]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
funcmaxSum(nums []int)int { ans := -1 maxVal := [10]int{} for i := range maxVal { maxVal[i] = math.MinInt // 表示不存在最大值 } for _, v := range nums { maxD := 0 for x := v; x > 0; x /= 10 { maxD = max(maxD, x%10) } ans = max(ans, v+maxVal[maxD]) maxVal[maxD] = max(maxVal[maxD], v) } return ans }
funcmax(a, b int)int { if b > a { return b }; return a }
[sol-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12
var maxSum = function (nums) { let ans = -1; let maxVal = Array(10).fill(Number.MIN_SAFE_INTEGER); for (const v of nums) { let maxD = 0; for (let x = v; x; x = Math.floor(x / 10)) maxD = Math.max(maxD, x % 10); ans = Math.max(ans, v + maxVal[maxD]); maxVal[maxD] = Math.max(maxVal[maxD], v); } return ans; };
复杂度分析
时间复杂度:\mathcal{O}(n\log U),其中 n 为 nums 的长度,U=max(\textit{nums})。