You are given a 0-indexed integer array nums
. You have to find the maximum sum of a pair of numbers from nums
such that the maximum digit in both numbers are equal.
Return the maximum sum or -1
if no such pair exists.
Example 1:
Input: nums = [51,71,17,24,42] Output: 88 Explanation: For i = 1 and j = 2, nums[i] and nums[j] have equal maximum digits with a pair sum of 71 + 17 = 88. For i = 3 and j = 4, nums[i] and nums[j] have equal maximum digits with a pair sum of 24 + 42 = 66. It can be shown that there are no other pairs with equal maximum digits, so the answer is 88.
Example 2:
Input: nums = [1,2,3,4] Output: -1 Explanation: No pair exists in nums with equal maximum digits.
Constraints:
2 <= nums.length <= 100
1 <= nums[i] <= 104
Solution: Brute Force
Enumerate all pairs of nums and check their sum and max digit.
Time complexity: O(n2)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Author: Huahua class Solution { public: int maxSum(vector<int>& nums) { auto maxDigit = [](int x) { int ans = 0; while (x) { ans = max(ans, x % 10); x /= 10; } return ans; }; int ans = -1; const int n = nums.size(); for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) if (nums[i] + nums[j] > ans && maxDigit(nums[i]) == maxDigit(nums[j])) ans = nums[i] + nums[j]; return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment