Skip to content

2522. Partition String Into Substrings With Values at Most K 👍

  • 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 minimumPartition(string s, int k) {
    int ans = 1;
    long curr = 0;

    for (const char c : s) {
      curr = curr * 10 + c - '0';
      if (curr > k) {
        curr = c - '0';
        ++ans;
      }
      if (curr > k)
        return -1;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int minimumPartition(String s, int k) {
    int ans = 1;
    long curr = 0;

    for (final char c : s.toCharArray()) {
      curr = curr * 10 + c - '0';
      if (curr > k) {
        curr = c - '0';
        ++ans;
      }
      if (curr > k)
        return -1;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def minimumPartition(self, s: str, k: int) -> int:
    ans = 1
    curr = 0

    for c in s:
      curr = curr * 10 + int(c)
      if curr > k:
        curr = int(c)
        ans += 1
      if curr > k:
        return -1

    return ans