Rijkstra的专栏

https://github.com/Ray137076517

【leetcode】Best Time to Buy and Sell Stock II

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).

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int result = 0;
        int profit = 0;
        if (prices.size() < 2)
            return result;
        for (vector<int>::iterator it = prices.begin() + 1; it != prices.end(); ++it)
        {
            profit = *it - *(it-1);
            if (profit > 0)
                result += profit;
        }
        return result;
    }
};


Personal Note

实际上就是求所有上升区段的幅度和。

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/C_Ray/article/details/49933361
个人分类: 练习 算法 C++
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

【leetcode】Best Time to Buy and Sell Stock II

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭