[leetcode] 122. Best Time to Buy and Sell Stock II

来源:互联网 发布:360浏览器安装js脚本 编辑:程序博客网 时间:2024/05/29 16:54

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 res =0;        for(int i=1; i< prices.size(); ++i){            if(prices[i]-prices[i-1]>0)                res += (prices[i] - prices[i-1]);        }        return res;    }};


0 0