
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maximum Value with Choice of Dividing or Considering in C++ Program
In this problem, we are given a number N. Our task is to create a program to find to Maximum value with the choice of either dividing or considering as it is in C++.
Problem Description
To find the maximum, we can consider any two values, either by take the value as it is or we could get the maximum value by dividing.The value could be extracted as F(N/2) + F(N/3) + F(N/4) + F(N/5).
Let’s take an example to understand the problem,
Input:N = 8
Output:9
Explanation
F(8) =F(8/2) + F(8/3) + F(8/4) + F(8/5) = F(4) + F(2) + F(2) + F(1) = 4 + 2 + 2 + 1 = 9
Solution Approach
The idea is simply to call the same function multiple times for the value of division. For this we have used the concept dynamic programming and created an array to solve the values of F(i) from 0 to N, for recusing them for finding the solution.
Example
#include <iostream> using namespace std; int calcMaximumValue(int N) { int F[N + 1]; int divVal = 0; F[0] = 0; F[1] = 1; for (int i = 2; i <= N; i++) { divVal = ( F[i / 2] + F[i / 3] + F[i / 4] + F[i / 5] ); if(divVal > i) F[i] = divVal; else F[i] = i; } return F[N]; } int main() { int N = 8; cout<<"Maximum value with the choice of either dividing or considering as it is = "<<calcMaximumValue(N); return 0; }
Output
Maximum value with the choice of either dividing or considering as it is = 9