Skip to content

2815. Max Pair Sum in an Array

  • Time: $O(\Sigma\log(\texttt{nums[i])})$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
 public:
  int maxSum(vector<int>& nums) {
    int ans = 0;
    // maxNum[i] := the maximum num we met so far with the maximum digit i
    vector<int> maxNum(10);

    for (const int num : nums) {
      const int d = getMaxDigit(num);
      if (maxNum[d] > 0)
        ans = max(ans, num + maxNum[d]);
      maxNum[d] = max(maxNum[d], num);
    }

    return ans == 0 ? -1 : ans;
  }

 private:
  int getMaxDigit(int num) {
    int maxDigit = 0;
    while (num > 0) {
      maxDigit = max(maxDigit, num % 10);
      num /= 10;
    }
    return maxDigit;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
  public int maxSum(int[] nums) {
    int ans = 0;
    // maxNum[i] := the maximum num we met so far with the maximum digit i
    int[] maxNum = new int[10];

    for (final int num : nums) {
      final int d = getMaxDigit(num);
      if (maxNum[d] > 0)
        ans = Math.max(ans, num + maxNum[d]);
      maxNum[d] = Math.max(maxNum[d], num);
    }

    return ans == 0 ? -1 : ans;
  }

  private int getMaxDigit(int num) {
    int maxDigit = 0;
    while (num > 0) {
      maxDigit = Math.max(maxDigit, num % 10);
      num /= 10;
    }
    return maxDigit;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  def maxSum(self, nums: list[int]) -> int:
    ans = 0
    # maxNum[i] := the maximum num we met so far with the maximum digit i
    maxNum = [0] * 10

    def getMaxDigit(num: int) -> int:
      maxDigit = 0
      while num > 0:
        maxDigit = max(maxDigit, num % 10)
        num //= 10
      return maxDigit

    for num in nums:
      d = getMaxDigit(num)
      if maxNum[d] > 0:
        ans = max(ans, num + maxNum[d])
      maxNum[d] = max(maxNum[d], num)

    return -1 if ans == 0 else ans