首页 > 代码库 > leetcode ——Best Time to Buy and Sell Stock II

leetcode ——Best Time to Buy and Sell Stock II

    遍历价格vector,把每段上升期间的利润加起来,注意最后结束时记得再计算最后一次的利润

技术分享

 

class Solution {    // 把每段上升期间的利润加起来    // minVal: 低谷值    // maxVal: 峰值    // profit: 利润public:    int maxProfit(vector<int> &prices) {        if(prices.empty()) return 0;        int maxVal(prices[0]), minVal(prices[0]), profit(0);        for(int i = 0; i != prices.size(); i ++){            // 若下降,则卖出股票:若prices[i] > maxVal,则下降            if(prices[i] < maxVal) {                profit += maxVal - minVal;                minVal = maxVal = prices[i];            }            // 若上升,则更改峰值            else{                maxVal = prices[i];            }        }        // 最后再计算一次利润,若maxVal - minVal > 0,则加入profit        if(maxVal - minVal > 0) profit += maxVal - minVal;        return profit;            }};

leetcode ——Best Time to Buy and Sell Stock II