leet_122_best_time_buy_and_sell(股票收益最大化2)

  • leet_code:链接
  • 问题描述:有一个数组,第i个元素代表第i天的股票价格,设计一个算法计算该股票收益的最大值,可以尽可能多的进行交易,但你必须没掉一只股票后才可以买另一只股票。
  • 输入输出样例:
    • Input1: [7,1,5,3,6,4]
    • Output1: 7
    • Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
      Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
    • Input2: [1,2,3,4,5]
    • Output: 4
    • Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
      Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
      engaging multiple transactions at the same time. You must sell before buying again.
  • 问题分析:
    分析
  • c++代码
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>

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

int main(int argc, char* argv[])
{
	vector<int> prices = {1,2,3,4,5,6};
	Solution solution;
	cout << solution.maxProfit(prices) << endl;
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值