## Interview Question

Software Engineer Industrial Placement Interview

-

# You have a given set of prices in an Array, find at which price you should buy and at which price you should sell so that you maximize the gain

1

The idea for the linear solution is, that when the next price is lower than current minimum, you should sell all for the previous maximum and buy for the new minimum. It is actually similar to looking for maximum difference where the min is predecessor of max. Code for the linear solution: void sell_points(const vector& data) { cout data[max]) { max = i; } } // last run if (data[min] < data[max] && max != last_max) { cout << "Buy:\t#" << min << " (price: " << data[min] << ")" << endl; cout << "Sell:\t#" << max << " (price: " << data[max] << ")" << endl; } }

Anonymous on

0

(the last_max check is actually not necessary, in the code I forgot to set it appropriately but it is not needed anyway)

Anonymous on

0

The brute-force solution is to compare each price to those further on and to return the greatest gain. Otherwise I tried a linear solution but I was not sure about the solution.

Anonymous on