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
Maximize the value of x + y + z such that ax + by + cz = n in C++
We are given with integers a,b,c,n. The goal is to maximize the sum of x, y and z such that ax+by+cz=n.
From above formula,
cz=n-(ax+by) z= (n- (ax+by))/c
By fixing x and y, calculate z using the above formula, for each x, y and z. Calculate sum and store the maximum such sum obtained.
Input
n = 6, a = 3, b = 4, c = 5;
Output
maximum x+y+z is 2.
Explanation − for x=2, y=0 and z=0 ax+by+cz=n.
3*2+0*4+0*5=6 = n
Input
n = 4, a = 3, b = 1, c = 2;
Output
maximum x+y+z=4
Explanation − for x=0, y=4 and z=4 ax+by+cz=n.
0*3+4*1+0*2=4 = n
Approach used in the below program is as follows
Integers a,b,c,and n are used for expression ax+by+cz=n.
Function maximize(,int n,int a,int b,int c) takes a, b, c and n as input and returns the maximum possible sum of x, y and z such that ax+by+cz=n.
Taking all possible ax values, for(i=0;i<=n;i+=a), also
Taking all possible by values for(j=0;j<=n;j+=b),
Calculate z= (n- (ax+by))/c.
Now x=i/a and y=j/b. Calculate x+y+z and store in temp.
If temp>=maxx so far, update maxx.
Return maxx as desired sum.
Example
#include <bits/stdc++.h>
using namespace std;
int maximize(int n, int a, int b, int c){
int maxx = 0;
// i for possible values of ax
for (int i = 0; i <= n; i += a)
// j for possible values of by
for (int j = 0; j <= n - i; j += b) {
float z = (n - (i + j)) / c;
// If z is an integer
if (floor(z) == ceil(z)) {
int x = i / a;
int y = j / b;
int temp=x+y+z;
if(temp>=maxx)
maxx=temp;
}
}
return maxx;
}
int main(){
int n = 6, a = 3, b = 4, c = 5;
cout <<"Maximized the value of x + y + z :"<<maximize(n, a, b, c);
return 0;
}
Output
Maximized the value of x + y + z :2