# Maximum number of segments of lengths a, b and c in C++

C++Server Side ProgrammingProgramming

Given the task is to find the maximum number of line segments of lengths a, b and c that can be formed from given positive integer N.

Let’s now understand what we have to do using an example −

Input − N=8, a=3, b=1, c=2

Output − 8

Explanation − N can be divided into 8 segments of b which is maximum number of segments that can be made.

Input − N=13, a=2, b=7, c=3

Output − 6

## Approach used in the below program as follows

• In function MaxSegment() declare an array MaxSeg[N +1] of type int and initialize it with value -1.

• The put the zero-th index equal to 0 as it will have no segments.

• Loop from i=0 till i<N and check if (MaxSeg[i]! = -1).

• Inside the above if statement put another statement if(i + a <=N) and put MaxSeg[i + a] = max(MaxSeg[i] + 1, MaxSeg[i + a]);

• Repeat the above step for both b and c.

• Outside the loop, return MaxSeg[N].

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int MaxSegment(int N, int a,int b, int c){
/* It will store the maximum number of segments each index can have*/
int MaxSeg[N + 1];
// initialization
memset(MaxSeg, -1, sizeof(MaxSeg));
// 0th index will have 0 segments
MaxSeg = 0;
// traversing for every segments till n
for (int i = 0; i < N; i++){
if (MaxSeg[i] != -1){
if(i + a <= N ){
MaxSeg[i + a] = max(MaxSeg[i] + 1, MaxSeg[i + a]);
}
if(i + b <= N ){
MaxSeg[i + b] = max(MaxSeg[i] + 1, MaxSeg[i + b]);
}
if(i + c <= N ){
MaxSeg[i + c] = max(MaxSeg[i] + 1, MaxSeg[i + c]);
}
}
}
return MaxSeg[N];
}
int main(){
int N = 13, a = 2, b = 7, c = 3;
cout << MaxSegment(N, a, b, c);
return 0;
}

## Output

If we run the above code we will get the following output −

6