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
- leetcode之Best Time to Buy and Sell StockII
- Leetcode 贪心 Best Time to Buy and Sell StockII
- leetcode Best Time to Buy and Sell
- LeetCode之Best Time to Buy and Sell Stock
- LeetCode之Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock III
- LeetCode 之 Best Time to Buy and Sell Stock
- LeetCode 之 Best Time to Buy and Sell Stock II
- LeetCode之Best Time to Buy and Sell Stock
- LeetCode之Best Time to Buy and Sell Stock II
- leetcode之Best Time to Buy and Sell Stock
- leetcode之Best Time to Buy and Sell Stock III
- leetcode之Best Time to Buy and Sell Stock
- leetcode之Best Time to Buy and Sell Stock II
- Leetcode之Best Time to Buy and Sell Stock
- leetcode 之 Best Time to Buy and Sell Stock
- Leetcode 之 Best Time to Buy and Sell StockI,II
- LeetCode之Best Time to Buy and Sell Stock III
- mapreduce程序实现排序
- dojo小例子(12)form转换成带内部对象的json数据
- j2ee规范13种
- jquery mobile如何实现滑动屏幕跳转页面
- 使用ImageSwitcher实现换图片
- leetcode之Best Time to Buy and Sell StockII
- uva10361 - Automatic Poetry
- 最大流和二分匹配
- HDU 4707 最后还是用了BFS。。。
- NYOJ 303 序号互换
- 将"2014-03-22"这个字符串转换成"2014年03月22日"日
- c++字符串详解(转)
- 构造、析构、继承对对象的影响
- 使用ImageSwitcher和Gallery实现左右滑动