The key idea is to replace each number with the sum of its digits, then find the minimum among these new values. Calculating the digit sum is straightforward and can be done for each element independently.
classSolution {
public:int minimumSum(vector<int>& nums) {
int ans = INT_MAX;
for (int x : nums) {
int s =0;
while (x) { s += x %10; x /=10; }
ans = min(ans, s);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
funcminimumSum(nums []int) int {
ans:=1<<30for_, x:=rangenums {
s:=0forx > 0 {
s+=x%10x/=10 }
ifs < ans { ans = s }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintminimumSum(int[] nums) {
int ans = Integer.MAX_VALUE;
for (int x : nums) {
int s = 0;
while (x > 0) {
s += x % 10;
x /= 10;
}
ans = Math.min(ans, s);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funminimumSum(nums: IntArray): Int {
var ans = Int.MAX_VALUE
for (x in nums) {
var s = 0var y = x
while (y > 0) {
s += y % 10 y /=10 }
ans = minOf(ans, s)
}
return ans
}
}
1
2
3
4
5
6
7
8
defminimum_sum(nums: list[int]) -> int:
defdigit_sum(x: int) -> int:
s =0while x:
s += x %10 x //=10return s
return min(digit_sum(x) for x in nums)
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnminimum_sum(nums: Vec<i32>) -> i32 {
nums.into_iter().map(|mut x| {
letmut s =0;
while x >0 {
s += x %10;
x /=10;
}
s
}).min().unwrap()
}
}
⏰ Time complexity: O(n * d), where n is the length of nums and d is the number of digits in the largest number. Each digit is processed once per number.
🧺 Space complexity: O(1), only a few variables are used for tracking the answer.