題目描述:
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.
代碼:
int maxProfit(vector&prices) { int length = prices.size(); if(length == 0) return 0; int max_profit = 0; int low = prices[0]; for(int i = 1;i < length;i++) { int temp = prices[i] - low; if(temp > max_profit) max_profit = temp; if(prices[i] < low) low = prices[i]; } return max_profit; }