Partitioning Into Minimum Number Of Deci-Binary Numbers

medium greedy string math

Problem

A number is deci-binary if every one of its digits is 0 or 1 (with no leading zeros), e.g. 101 and 1100. Given a string n representing a positive decimal integer, return the minimum number of positive deci-binary numbers that sum to n.

Inputn = "32"
Output3
10 + 11 + 11 = 32. The largest digit is 3, so 3 numbers are required.
Inputn = "82734"
Output8
The largest digit anywhere in the string is 8.

def min_partitions(n):
    best = 0
    for ch in n:
        d = ord(ch) - ord('0')
        if d > best:
            best = d
        if best == 9:
            break
    return best
function minPartitions(n) {
  let best = 0;
  for (let i = 0; i < n.length; i++) {
    const d = n.charCodeAt(i) - 48;
    if (d > best) best = d;
    if (best === 9) break;
  }
  return best;
}
int minPartitions(String n) {
    int best = 0;
    for (int i = 0; i < n.length(); i++) {
        int d = n.charAt(i) - '0';
        if (d > best) best = d;
        if (best == 9) break;
    }
    return best;
}
int minPartitions(string n) {
    int best = 0;
    for (char ch : n) {
        int d = ch - '0';
        if (d > best) best = d;
        if (best == 9) break;
    }
    return best;
}
Time: O(L) Space: O(1)