您的位置:首页 > 其它

Best Time to Buy and Sell Stock II

2015-06-17 20:44 288 查看
Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock
before you buy again).

解题思路:

因为本题要求我们在取得最优值的前提下,能进行更多的交易就进行更多的交易。

假设存在三个点x1, x2, x3,并且满足 x1 < x2 < x3,如果我们选x1和x3和我们选x1,x2和x2,x3获得的收益是相同的。但是当x1<x2=x3时,我们选x1和x2得到的结果不会比选x1和x3得到的结果差,因此在此处计算的时候我们采用贪心的算法。

class Solution {
public:
    /* 贪心求解 */
    int maxProfit(vector<int>& prices) {
        int ans = 0;
        int minv;
        int n = prices.size();
        if(n <= 1) return 0;
        minv = prices[0];
        for(int i = 1; i < n; ++i) {
            if(prices[i] > minv) {
                ans += (prices[i] - minv);
                minv = prices[i];
            } else {
                minv = min(minv, prices[i]);
            }
        }
        return ans;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: