122. Best Time to Buy and Sell Stock II

来源:互联网 发布:释行宇谭腿 知乎 编辑:程序博客网 时间:2024/06/07 13:51

122. 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 dayi.

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

        这个题在121(Best Time to Buy and Sell Stock)题的基础上增加了可以买卖多次,但是在买之前必须把之前买的卖掉。这个地方一开始我自以为是不可以同一天买卖,想了好久,后来才发现这一问题。如果,可以同一天买卖,那么对于一个递增的子序列[1,2,3,5,6,8,9],从1直接算到9(1,9)和一个数一个数(1,2)+(2,3)+(3,5)+(5,6)+(6,8)+(8,9)算到9,结果是一样的,所以只需要比较前一个数和后一个数的大小,如果后数大于前数则加两者之和,扫描到数列尾,即得结果。

class Solution {public:int maxProfit(vector<int>& prices) {int m = 0;if (prices.empty()) return m;for (int i = 0; i < prices.size() - 1; i++) if (prices[i] < prices[i + 1]) m = m + prices[i + 1] - prices[i];return m;}};

0 0
原创粉丝点击