Best Time to Buy and Sell Stock II(leetcode)

题目:

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

题目来源:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

解题思路:把股票数组的股票值画成一位曲线,取每一段的单调上升区间的开头买入,结尾处卖出,多次之和就是最大的利益

《leetcode题解》中有更简单的算法,其实思想类似,只是代码短:每当当前值比前一个值大时,就将增加的值累加到maxProf中,当扫描整个数组后,即可以得到最大的收益。

#include<iostream>
#include<vector>
using namespace std;

int maxProfit(vector<int> &prices)
{
	if(prices.empty())
		return 0;
	int lo=0,maxProf=0;
	int i=0;
	for(i=0;i<prices.size()-1 && prices[i]>=prices[i+1];i++)
		;
	if(i==prices.size()-1)
		return 0;
	lo=prices[i];
	int increase=1;
	for(int j=i;j<prices.size()-1;j++)
	{
		if(prices[j]>prices[j+1] && increase==1)//开始下降
		{
			increase=0;
			maxProf+=prices[j]-lo;
			lo=0;
		}
		if(prices[j]<prices[j+1] && increase==0)//开始上升
		{
			increase=1;
			lo=prices[j];
		}
	}
	if(increase==1)//如果到最后一个点仍然是上升趋势
		maxProf+=prices[prices.size()-1]-lo;
	return maxProf;
}

int main()
{
	vector<int> prices;
	prices.push_back(1);
	prices.push_back(4);
	prices.push_back(2);
	cout<<maxProfit(prices)<<endl;

	system("pause");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值