Given A,B and n find the minimum value of Ax-By where x+y = n

137 Views Asked by At

Given $A$, $B$, $n$ we're interested in non negative values $Ax-By$, where $A,B,n$ $\in$ $\mathbb Z$, n $\le$ $10^5$, $A+B=n$ and the value of the equation is minimized in case of multiple possible values of $x,y$

My idea is nothing but plain bruteforce, checking each values from $i$ to $n$ and $n-i$,thus finding minimum value.

For example:

$A=5,B=6$

$6*5 - 4*6 = 6$

Need some efficient ideas. Thanks in advance.

1

There are 1 best solutions below

0
On BEST ANSWER

$y=n-x$ and you minimize $$Ax-B(n-x)=(A+B)x-Bn.$$

All values taken by this expression differ in multiples of $A+B$, and the smallest positive value is

$$(-Bn)\bmod(A+B),$$ which is in $[0,A+B)$.


UPDATE:

The conditions in the title and in the body define completely different problems !