- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- 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 Articles
- C++ program to find maximum how many chocolates we can buy with at most k rupees
- C++ program to find minimum how many coins needed to buy binary string
- Find minimum cost to buy all books in C++
- Find the minimum and maximum amount to buy all N candies in Python
- Program to find minimum number of roads we have to make to reach any city from first one in C++
- Python program to find ways to get n rupees with given coins
- C++ Program to find which episode we have missed to watch
- Find out the minimum number of coins required to pay total amount in C++
- C++ Program to find minimum possible ugliness we can achieve of towers
- Program to find minimum number of days to eat N oranges in Python
- C++ code to find minimum different digits to represent n
- Program to find minimum number of flips required to have alternating values in Python
- Program to find minimum number of Fibonacci numbers to add up to n in Python?
- C++ Program to find out the minimum difference value in n integer pairs
- C++ program to check we can buy product with given money or not

Advertisements