#3079
Find the Sum of Encrypted Integers
EasyArrayMathArrayMath
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of constructing the encrypted number by string manipulation, we can directly calculate the sum using the largest digit and the number of digits in each number. This avoids unnecessary string operations and speeds up the process.
⚙️
Algorithm
6 steps- 1Step 1: Initialize a variable to hold the total sum.
- 2Step 2: For each number in the input array, find the maximum digit.
- 3Step 3: Determine the number of digits in the number.
- 4Step 4: Calculate the encrypted number directly as maxDigit * (10^numberOfDigits - 1) / 9.
- 5Step 5: Add the encrypted number to the total sum.
- 6Step 6: Return the total sum.
solution.py13 lines
1# Full working Python code
2
3def encrypt_sum_optimal(nums):
4 total_sum = 0
5 for num in nums:
6 max_digit = max(int(d) for d in str(num))
7 number_of_digits = len(str(num))
8 encrypted_num = max_digit * (10**number_of_digits - 1) // 9
9 total_sum += encrypted_num
10 return total_sum
11
12# Example usage
13print(encrypt_sum_optimal([10, 21, 31])) # Output: 66ℹ
Complexity note: The time complexity is O(n) because we only iterate through the array once, and for each number, we find the maximum digit and calculate the encrypted number in constant time. This is much more efficient than the brute force approach.
- 1The encrypted number can be derived directly from the maximum digit and the number of digits in the original number.
- 2Understanding how to manipulate numbers and strings efficiently is key to optimizing solutions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.