【貪心演算法】49. Best Time to Buy and Sell Stock
阿新 • • 發佈:2018-11-27
49. 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.
Example
Given array [3,2,3,1,2]
, return 1
.
class Solution { public: /** * @param prices: Given an integer array * @return: Maximum profit */ int maxProfit(vector<int> &prices) { // write your code here if(prices.size()==0) return 0; int min = prices.at(0);int max = 0; for(int i = 0;i<prices.size();i++){ if(min>prices.at(i)) min = prices.at(i); else max = max>(prices.at(i)-min)? max : (prices.at(i)-min); } return max; } };