关闭

【leetcode】Best Time to Buy and Sell Stock II

179人阅读 评论(0) 收藏 举报
分类:

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

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

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:5879次
    • 积分:252
    • 等级:
    • 排名:千里之外
    • 原创:20篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类