Maximum segment value after putting k breakpoints in a number | CPP program to find the maximum segment value after putting k breaks . ; Function to Find Maximum Number ; Maximum segment length ; Find value of first segment of seg_len ; Find value of remaining segments using sliding window ; To find value of current segment , first remove leading digit from previous value ; Then add trailing digit ; Driver 's Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxSegment ( string & s , int k ) { int seg_len = s . length ( ) - k ; int res = 0 ; for ( int i = 0 ; i < seg_len ; i ++ ) res = res * 10 + ( s [ i ] - '0' ) ; int seg_len_pow = pow ( 10 , seg_len - 1 ) ; int curr_val = res ; for ( int i = 1 ; i <= ( s . length ( ) - seg_len ) ; i ++ ) { curr_val = curr_val - ( s [ i - 1 ] - '0' ) * seg_len_pow ; curr_val = curr_val * 10 + ( s [ i + seg_len - 1 ] - '0' ) ; res = max ( res , curr_val ) ; } return res ; } int main ( ) { string s = "8754" ; int k = 2 ; cout << " Maximum ▁ number ▁ = ▁ " << findMaxSegment ( s , k ) ; return 0 ; }