leetcode之Best Time to Buy and Sell StockII

来源:互联网 发布:中国最大的unity3d论坛 编辑:程序博客网 时间:2024/05/29 02:35

题目大意:

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

意思就是:

有一个整型数组,代表股票的价格。你有多次买入和卖出的机会,请你设计一个算法,使你的收益最大。——本题与第一道题的区别是,第一题只有一次买入和卖出的机会,但本题有很多次机会。

思路:

贪心算法思路。从第1个数组元素开始,找到最大的利润,直到第i个元素不增,只减,则记下此次的利润(作为一次卖出机会);从i+1继续求下一次最大的利润。直到整个数组都算完。

代码如下:

class Solution {public:    int maxProfit(vector<int> &prices) {        vector<int>::size_type length = prices.size();vector<int> result;if(length == 0){return 0;}int i = 1, min = prices[0], profit = 0;while(i<length){if(prices[i] > prices[i-1]){profit = (prices[i] - min > profit)?(prices[i] - min):profit;min = (prices[i]>min)?min:prices[i];}else{min = prices[i];result.push_back(profit);profit = 0;}i++;}result.push_back(profit);int max_profit = 0;for(i=0;i<result.size();i++){max_profit += result[i];}return max_profit;    }};


0 0
原创粉丝点击