leetcode--Best Time to Buy and Sell Stock II

来源:互联网 发布:w3cschool php教程 编辑:程序博客网 时间:2024/05/29 04:41

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 i=0;        int m_profit=0;        int l=prices.size();        for (i;i<l-1;i++)        {            if (prices[i]<prices[i+1])            m_profit+=prices[i+1]-prices[i];}        return m_profit;    }};
0 0
原创粉丝点击