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

C++Server Side ProgrammingProgramming

Problem statement

Given a large number as string s and an integer k which denotes the number of breakpoints we must put in the number k <= string length. The task is to find maximum segment value after putting exactly k breakpoints.

Example

Example
If s = 313 and k = 1 then we can obtain 31 as maximum number.
We can form 2 numbers by putting 1 breakpoint:
1. 3 and 13
2. 31 and 3. And maximum is 31

Algorithms

  • The maximum would always be of length “string-lengths – k” which is the maximum value of any segment
  • Considering the fact, problem becomes like sliding window problem means we need to find maximum of all substrings of size (string-length – k)

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMaxSegment(string &str, int k) {
   int segLength = str.length() - k;
   int result = 0;
   for (int i = 0; i < segLength; ++i) {
      result = result * 10 + str[i] - '0';
   }
   int segLenPow = pow(10, segLength - 1);
   int curVal = result;
   for (int i = 1; i <= (str.length() - segLength); ++i) {
      curVal = curVal - (str[i - 1] - '0') *  segLenPow;
      curVal = curVal * 10 + (str[i + segLength - 1]- '0');
      result = max(result, curVal);
   }
   return result;
}
int main() {
   string str = "313";
   int k = 1;
   cout << "Maximum number = " << getMaxSegment(str, k) << endl;
   return 0;
}

Output

When you compile and execute above program. It generates following output −

Maximum number = 31
raja
Published on 21-Jan-2020 11:24:32
Advertisements