

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
C++ program to find minimum how much rupees we have to pay to buy exactly n liters of water
Suppose we have three numbers n, a and b. We want to buy n liters of water. There are only two types of water bottles nearby, 1-liter bottles and 2-liter bottles. The bottle of the first type a rupees and the bottle of the second type costs b rupees. We want to spend as few money as possible. We have to find the minimum amount of money we need to buy exactly n liters of water.
So, if the input is like n = 7; a = 3; b = 2, then the output will be 9, because with 3 2-liter bottles we can get 6 liters of water with price 6, then one 1 liter bottle is needed for cost 3.
Steps
To solve this, we will follow these steps −
b := minimum of a * 2 and b return (n / 2 * b) + (n mod 2) * a
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; int solve(int n, int a, int b) { b = min(a * 2, b); return n / 2 * b + n % 2 * a; } int main() { int n = 7; int a = 3; int b = 2; cout << solve(n, a, b) << endl; }
Input
7, 3, 2
Output
9
- Related Questions & Answers
- C++ program to find maximum how many chocolates we can buy with at most k rupees
- Python program to find ways to get n rupees with given coins
- C++ program to find minimum how many coins needed to buy binary string
- Find the minimum and maximum amount to buy all N candies in Python
- Maximum litres of water that can be bought with N Rupees in C++
- Find minimum cost to buy all books in C++
- Program to find maximum how many water bottles we can drink in Python
- Program to find minimum number of roads we have to make to reach any city from first one in C++
- Program to find minimum number of flips required to have alternating values in Python
- Find out the minimum number of coins required to pay total amount in C++
- C++ Program to find which episode we have missed to watch
- Program to find minimum number of days to eat N oranges in Python
- Program to find minimum number of Fibonacci numbers to add up to n in Python?
- Program to find total amount of money we have in bank in Python
- C++ Program to find minimum possible ugliness we can achieve of towers
Advertisements