LeetCode 122. Best Time to Buy and Sell Stock II

来源:互联网 发布:java开源架构 编辑:程序博客网 时间:2024/05/29 16:50

描述

给出一支股票在每天的价格,求在允许多次交易的情况下可以获得的最大收益

解决

记录当前天的最小值,遇到比当前天价格高的就卖出,然后重新买入,买入之前先卖出。

class Solution {public:    int maxProfit(vector<int>& prices) {        int lenth = prices.size();        int tmp = 0x3f3f3f, res = 0;        for (int i = 0; i < lenth; ++i){            if (prices[i] <= tmp){                tmp = prices[i];            }            else if (prices[i] > tmp){                res += prices[i] - tmp;                tmp = prices[i];            }        }        return res;    }};
0 0
原创粉丝点击