Given two integers X and Y, and two values cost1 and cost2, the task is to convert the given two numbers equal to zero at minimal cost by performing the following two types of operations:
- Increase or decrease any one of them by 1 at cost1.
- Increase or decrease both of them by 1 at cost2.
Examples:
Input: X = 1, Y = 3, cost1 = 391, cost2 = 555
Output: 1337
Explanation:
Reduce Y to 1 using the first operation twice and convert both X and Y from 1 to 0 using the second operation.
Hence, the total cost = 391 * 2 + 555 = 1337.
Input: X = 12, Y = 7, cost1 = 12, cost2 = 7
Output: 4
Explanation:
Reduce X to 7 using first operation and then convert both X and Y to 0 using the second operation.
Hence, the total cost = 12 * 5 + 7 * 7 = 109
Approach:
The most optimal way to solve the problem is:
- Reduce the maximum of X and Y to the minimum by using first operation. This increases the cost by abs(X – Y) * cost1.
- Then, reduce both X and Y to 0 using the second operation. This increase the cost by minimum of (X, Y) * cost2.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int makeZero( int x, int y, int a, int b)
{
if (x > y)
x = y,
y = x;
int tot_cost = (y - x) * a;
int cost1 = 2 * x * a;
int cost2 = x * b;
tot_cost += min(cost1, cost2);
cout << tot_cost;
}
int main()
{
int X = 1, Y = 3;
int cost1 = 391, cost2 = 555;
makeZero(X, Y, cost1, cost2);
}
|
Java
import java.util.*;
class GFG{
static void makeZero( int x, int y, int a, int b)
{
if (x > y)
{
int temp = x;
x = y;
y = temp;
}
int tot_cost = (y - x) * a;
int cost1 = 2 * x * a;
int cost2 = x * b;
tot_cost += Math.min(cost1, cost2);
System.out.print(tot_cost);
}
public static void main(String args[])
{
int X = 1 , Y = 3 ;
int cost1 = 391 , cost2 = 555 ;
makeZero(X, Y, cost1, cost2);
}
}
|
Python3
def makeZero(x, y, a, b):
if (x > y):
x, y = y, x
tot_cost = (y - x) * a
cost1 = 2 * x * a
cost2 = x * b
tot_cost + = min (cost1, cost2)
print (tot_cost)
if __name__ = = "__main__" :
X, Y = 1 , 3
cost1, cost2 = 391 , 555
makeZero(X, Y, cost1, cost2)
|
C#
using System;
class GFG{
static void makeZero( int x, int y, int a, int b)
{
if (x > y)
{
int temp = x;
x = y;
y = temp;
}
int tot_cost = (y - x) * a;
int cost1 = 2 * x * a;
int cost2 = x * b;
tot_cost += Math.Min(cost1, cost2);
Console.Write(tot_cost);
}
public static void Main()
{
int X = 1, Y = 3;
int cost1 = 391, cost2 = 555;
makeZero(X, Y, cost1, cost2);
}
}
|
Javascript
<script>
function makeZero(x, y, a, b)
{
if (x > y)
{
let temp = x;
x = y;
y = temp;
}
let tot_cost = (y - x) * a;
let cost1 = 2 * x * a;
let cost2 = x * b;
tot_cost += Math.min(cost1, cost2);
document.write(tot_cost);
}
let X = 1, Y = 3;
let cost1 = 391, cost2 = 555;
makeZero(X, Y, cost1, cost2);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)