Find the Sum of Encrypted Integers Problem
#3079
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3079.
You are given an integer array nums containing positive integers. We define a function encrypt such that encrypt(x) replaces every digit in x with the largest digit in x. For example, encrypt(523) = 555 and encrypt(213) = 333.
Return the sum of encrypted elements.
Example 1:
Input: nums = [1,2,3]
Output: 6
Explanation: The encrypted elements are [1,2,3]. The sum of encrypted elements is 1 + 2 + 3 == 6.
Example 2:
Input: nums = [10,21,31]
Output: 66
Explanation: The encrypted elements are [11,22,33]. The sum of encrypted elements is 11 + 22 + 33 == 66.
Constraints:
1 <= nums.length <= 501 <= nums[i] <= 1000
Solution
Approach: Simulation
Write encrypt(x) directly. Peel digits off x with % 10 and / 10, tracking the largest digit mx, and build p = 1, 11, 111, ... with one more 1 per digit. The encrypted value is mx * p. The answer is the sum over all numbers.
Complexity: O(n log M) time, O(1) space, where M is the largest value in nums.
class Solution:
def sumOfEncryptedInt(self, nums: List[int]) -> int:
def encrypt(x: int) -> int:
mx = p = 0
while x:
x, v = divmod(x, 10)
mx = max(mx, v)
p = p * 10 + 1
return mx * p
return sum(encrypt(x) for x in nums)