Maximum segment value after putting k breakpoints in a number in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a string that denotes a large number and an integer k roar denotes the number of breakpoints. Our task is to create a program that will find the maximum segment value after putting L breakpoints in a number.

Here, we have to find the maximum number that can be generated after putting k breakpoint in the number given by the string.

Let's take an example to understand the problem

Input − string = “45972”, k = 3

Output − 97


All possible number is:
45    9    7    2
4    59    7    2
4    5    97    2
4    5    9    72
From all 97 is the largest number.

To solve this problem, we will use the sliding window. Here, the window size will be equal to (length of string - k) i.e. the maximum number will of this size. We will check for the maximum number form all the possible numbers of the given size using the sliding window technique.


Program to find the maximum segment value after putting K breakpoints in a number −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int findMaxSegmentWithKbreaks(string &s, int k) {
   int window = s.length() - k;
   int MaxNumber = 0;
   for (int i=0; i<window; i++)
   MaxNumber = MaxNumber * 10 + (s[i] - '0');
   int slWindow = pow(10, window-1);
   int value = MaxNumber;
   for (int i = 1; i <= (s.length() - window); i++) {
      value = value - (s[i-1]- '0')*slWindow;
      value = value*10 + (s[i+window-1]- '0');
      MaxNumber = max(MaxNumber, value);
   return MaxNumber;
int main() {
   string s = "45972";
   int k = 3;
   cout<<"Maximum segment value after putting "<<k<<" break points in a number = "<<findMaxSegmentWithKbreaks(s, k);
   return 0;


Maximum segment value after putting 3 breakpoints in a number = 97
Published on 21-Jan-2020 15:54:32