Tuesday, September 23, 2014

Best Time to Buy and Sell Stock

Problem

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Idea

用一个变量minVal记录当前最小的value, profit记录当前最大的差价。 遍历整个List, 对于每一个prices[i]比较 profit和pricesp[i]-minVal谁大。 并更新minVal和profit.

Solution


No comments:

Post a Comment