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.
给定一个数组prices, prices[i]表示第i天的股价。只允许做一次股票交易(只能一次买入,一次卖出),要求计算最大获利是多少?
class Solution { public: int maxProfit(vector<int> &prices) { int size=prices.size(); if(size<=1)return 0; int maxProfit=0; int minPrice=INT_MAX; for(int i=0; i<size; i++){ if(minPrice!=INT_MAX){ //计算第i天卖出的最大收益 if(prices[i]-minPrice > maxProfit) maxProfit=prices[i]-minPrice; } //更新最小股价 if(prices[i]<minPrice)minPrice=prices[i]; } return maxProfit; } };
LeetCode: Best Time to Buy and Sell Stock [121],布布扣,bubuko.com
LeetCode: Best Time to Buy and Sell Stock [121]
原文:http://blog.csdn.net/harryhuang1990/article/details/28850365