Thursday 3 December 2015

Stock Buy Sell for Maximum Profit

The cost of a stock on a day is given in a list, find the max profit that we can make by buying and selling once.

Example:
If the given array is {90, 170, 700, 300, 30, 525, 685}.
Maximum profit: 685 – 30.

90
170
700
300
30
525
685

Solution:
90
170
700
300
30
525
685

minArray[]: Minimum element in left sub-array of every index.
90
90
90
90
30
30
30

maxArray[]: Maximum element in right sub-array of every index.
700
700
700
685
685
685
685

difference[]: Difference of minArray[i]-maxArray[i].
610
610
610
595
655
655
655


Maximum value in difference array will be treated as result.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...