Spurs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

122. Best Time to Buy and Sell Stock II

为获得最高收益而多次买卖,但只能像这样买卖: 针对 [7, 1, 5, 3, 6, 4], 我们 buy 1, sell 5; buy 3, sell 6.

\(O(n)\) time, \(O(1)\) space.

自家代码:

//这代码就简单了
//  7   1   5   3   6   4
//      B   S   B   S
int maxProfit(vector<int>& A) {
    int i, temp, p = 0, profit = 0;
    for (i = 1; i < A.size(); i++) {
        temp = A[i] - A[i - 1];
        p = 0 > temp ? 0 : temp;
        profit += p;
    }
    return profit;
}
posted on 2017-08-14 11:55  英雄与侠义的化身  阅读(64)  评论(0编辑  收藏  举报