Count digit groupings of a number with given constraints | Maximum length of input number string ; A memoization table to store results of subproblems length of string is 40 and maximum sum will be 9 * 40 = 360. ; Function to find the count of splits with given condition ; Terminating Condition ; If already evaluated for a given sub problem then return the value ; countGroups for current sub - group is 0 ; sum of digits ; Traverse all digits from current position to rest of the length of string ; If forward_sum is greater than the previous sum , then call the method again ; Note : We pass current sum as previous sum ; total number of subgroups till current position ; Driver Code ; Initialize dp table
let MAX = 40 ; let dp = new Array ( MAX ) ; function countGroups ( position , previous_sum , length , num ) { if ( position == length ) return 1 ; if ( dp [ position ] [ previous_sum ] != - 1 ) return dp [ position ] [ previous_sum ] ; dp [ position ] [ previous_sum ] = 0 ; let res = 0 ; let sum = 0 ; for ( let i = position ; i < length ; i ++ ) { sum += ( num [ i ] - ' ' ) ; if ( sum >= previous_sum ) res += countGroups ( i + 1 , sum , length , num ) ; } dp [ position ] [ previous_sum ] = res ; return res ; } let num = " " . split ( " " ) ; let len = num . length ; for ( let i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = new Array ( 9 * MAX + 1 ) for ( let j = 0 ; j < 9 * MAX + 1 ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } document . write ( countGroups ( 0 , 0 , len , num ) ) ;