LeetCode 2522: Partition String Into Substrings With Values at Most K

Problem Description

Explanation:

To solve this problem, we can iterate through the given string s and maintain a running sum of the current substring value. If the value of the current substring exceeds k, we increment the count of substrings and reset the running sum.

Algorithm:

  1. Initialize variables count to store the number of substrings, curValue to store the current substring value, and i as the index.
  2. Iterate over the characters in the string s.
  3. For each character:
    • Calculate the integer value of the character.
    • Update curValue by multiplying it by 10 and adding the integer value.
    • If curValue exceeds k, increment count and reset curValue to the integer value of the current character.
  4. Finally, check if curValue is greater than 0. If so, increment count.
  5. If there are no good partitions (i.e., count is 0), return -1. Otherwise, return count.

Time Complexity:

The time complexity of this algorithm is O(n), where n is the length of the input string s.

Space Complexity:

The space complexity is O(1) as we are using a constant amount of extra space.

:

Solutions

class Solution {
    public int partitionString(String s, int k) {
        int count = 0;
        int curValue = 0;
        
        for (int i = 0; i < s.length(); i++) {
            int digitValue = s.charAt(i) - '0';
            curValue = curValue * 10 + digitValue;
            
            if (curValue > k) {
                count++;
                curValue = digitValue;
            }
        }
        
        if (curValue > 0) {
            count++;
        }
        
        return count == 0 ? -1 : count;
    }
}

Loading editor...