Question

Given sum of A and B let S i have to find maximum product of A*B but there is one condition value of A will be in range [P,Q]

How to proceed for it ?

If there is no range then task is pretty simple.

Using derivation method .

How to find Maximum product for eg.

A+B=99 value of A will be range [10,20]

then what will be the maximum product of A and B.

O(N) will not sufficient for the problem

Était-ce utile?

La solution

Clearly, B = S - A and you need to maximize A * (S - A).

You know from algebra that A * (S - A) achieves a maximum when A = S / 2.

If S / 2 falls in the allowed range [P Q], then the maximum value is A^2 / 4.

Otherwise, by monotonicity the maximum value is reached at one of the bounds and is the largest of P * (S - P) and Q * (S - Q).

This is an O(1) solution.

Autres conseils

This is actually a maths question, nothing to do with programming

Even if you are given it as a programming question, You should first understand it mathematically.

You can think of it geometrically as "if the perimeter of my rectangle is fixed at S, how can I achieve the maximum area?"

The answer is by making sides of equal length, and turning it into a square. If you're constrained, you have to get as close to a square as possible.

You can use calculus to show it formally:

A+B = S, so B = S-A

AB therefore = A(S-A)

A is allowed to vary, so write it as x

y = x(S-x) = -x^2 + Sx

This is a quadratic, its graph Will look like an upsidedown parabola

You want the maximum, so you're looking for the top of the parabola

dy/dx = 0

-2x + S = 0

x = S/2

A better way of looking at it would be to start with our rectangle Pq = A, and say P is the longer edge.

So now make it more oblique, by making the longer edge P slightly longer and the shorter edge q slightly shorter, both by the same amount, so P+q does not change, and we can show that the area goes down:

Pq = A

(P+delta) * (q-delta) 
    = Pq + (q-P)*delta + delta^2  
    = A + (q-P)delta

and I throw away the delta^2 as it vanishes as delta shrinks to 0

    = A + (something negative)*delta
    = A - something positive

i.e. < A

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top