题解 | #买卖股票的最好时机(一)#
买卖股票的最好时机(一)
https://www.nowcoder.com/practice/64b4262d4e6d4f6181cd45446a5821ec
class Solution { public: /** * * @param prices int整型vector * @return int整型 */ int maxProfit(vector<int>& prices) { // write code here //局部最优解 int value = 0; int min = prices[0]; int minIndex = 0; int max = prices[0]; int maxIndex = 0; int i = 0; while (i<prices.size()) { if (prices[i]>max) { max = prices[i]; maxIndex = i; } if (prices[i]<min) { min = prices[i]; minIndex = i; max = 0; } if (maxIndex>minIndex) { value = value>(max-min)?value:(max-min); } i++; } return value; } };