Maximize the number of segments of length p, q and r in C++


Problem statement

Given a rod of length L, the task is to cut the rod in such a way that the total number of segments of length p, q and r is maximized. The segments can only be of length p, q, and r

If l = 15, p = 2, q = 3 and r = 5 then we can make 7 segments as follows −

{2, 2, 2, 2, 2, 2, 3}

Algorithm

We can solve this problem using dynamic programming

1. Initialize dp[] array to 0
2. Iterate till the length of the rod. For every i, a cut of p, q and r if possible is done.
3. Initialize ans[i+p] = max( ans[i+p], 1 + ans[i]), ans[i+q] = max(ans[i+q], 1 + ans[i]) and ans[i+r] = max(ans[i+r], 1 + ans[i]) for all the possible cuts.
4. ans[i] will be 0 if a cut at i-th index is not possible. ans[l] will give the maximum number of cuts possible

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMaximumSegments(int l, int p, int q, int r){
   int dp[l + 1];
   memset(dp, -1, sizeof(dp));
   dp[0] = 0;
   for (int i = 0; i <= l; ++i) {
      if (dp[i] == -1) {
         continue;
      }
      if (i + p <= l) {
         dp[i + p] = max(dp[i + p], dp[i] + 1);
      }
      if (i + q <= l) {
         dp[i + q] = max(dp[i + q], dp[i] + 1);
      }
      if (i + r <= l) {
         dp[i + r] = max(dp[i + r], dp[i] + 1);
      }
   }
   return dp[l];
}
int main(){
   int l = 15, p = 2, q = 3, r = 5;
   cout << "Number of segments = " << getMaximumSegments(l, p, q, r) << endl;
   return 0;
}

Output

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

Number of segments = 7

Updated on: 24-Dec-2019

105 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements