Teaching Kids Programming – Minimum Sum of Four Digit Number After Splitting Digits


Teaching Kids Programming: Videos on Data Structures and Algorithms

You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used.

For example, given num = 2932, you have the following digits: two 2’s, one 9 and one 3. Some of the possible pairs [new1, new2] are [22, 93], [23, 92], [223, 9] and [2, 329].
Return the minimum possible sum of new1 and new2.

Example 1:
Input: num = 2932
Output: 52
Explanation: Some possible pairs [new1, new2] are [29, 23], [223, 9], etc.
The minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52.

Example 2:
Input: num = 4009
Output: 13
Explanation: Some possible pairs [new1, new2] are [0, 49], [490, 0], etc.
The minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13.

Constraints:
1000 <= num <= 9999

Minimum Sum of Four Digit Number After Splitting Digits (Greedy Algorithm)

The Greedy idea is to split the digits, and put the larger digit at One’s and smaller digits at Ten’s.

We are sorting 4 digits.

1
2
3
4
class Solution:
    def minimumSum(self, num: int) -> int:
        s = sorted(map(int, list(str(num))))
        return s[0] * 10 + s[3] + s[1] * 10 + s[2]
class Solution:
    def minimumSum(self, num: int) -> int:
        s = sorted(map(int, list(str(num))))
        return s[0] * 10 + s[3] + s[1] * 10 + s[2]

Time/space complexity is O(1) since the problem is bounded.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
333 words
Last Post: Teaching Kids Programming - Compound Interests and Euler's number (Math Constant E)
Next Post: Teaching Kids Programming - Nearest Exit from Entrance in Maze via Breadth First Search Algorithm (BFS)

The Permanent URL is: Teaching Kids Programming – Minimum Sum of Four Digit Number After Splitting Digits

Leave a Reply