Skip to content

3300. Minimum Element After Replacement With Digit Sum 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int minElement(vector<int>& nums) {
    int ans = INT_MAX;
    for (const int num : nums)
      ans = min(ans, getDigitSum(num));
    return ans;
  }

 private:
  int getDigitSum(int num) {
    int digitSum = 0;
    while (num > 0) {
      digitSum += num % 10;
      num /= 10;
    }
    return digitSum;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int minElement(int[] nums) {
    int ans = Integer.MAX_VALUE;
    for (final int num : nums)
      ans = Math.min(ans, getDigitSum(num));
    return ans;
  }

  private int getDigitSum(int num) {
    int digitSum = 0;
    while (num > 0) {
      digitSum += num % 10;
      num /= 10;
    }
    return digitSum;
  }
}
1
2
3
class Solution:
  def minElement(self, nums: list[int]) -> int:
    return min(sum(map(int, str(num))) for num in nums)