地址:http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/
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.
思路:交易是先买后卖,所以记录下当前为止的最小值min_value,和当前前一次的最大收益ret,赋值ret为ret和当前值与min_value差的较大值。c++参考代码:
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.empty())
return 0;
int ret=-1, min_val=0x7fffffff;
for(int i=0; i<prices.size(); ++i)
{
min_val = min(min_val, prices[i]);
ret = max(ret, prices[i]-min_val);
}
return ret;
}
};
python代码:
class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
if not prices:
return 0
cur_min = prices[0]
m = 0
for i in prices:
m = max(m, i-cur_min)
cur_min = min(cur_min, i)
return m
//SECOND TRIAL, almost the sameclass Solution {public :int maxProfit ( vector < int > & prices ) {if ( prices . size () <= 1 )return 0 ;int ans = 0 , pre_min = prices [ 0 ];for ( int i = 1 ; i < prices . size (); ++ i ){pre_min = min ( pre_min , prices [ i ]);ans = max ( ans , prices [ i ] - pre_min );}return ans ;}};