LeetCode刻意练习06--买卖股票的最佳时机

买卖股票的最佳时期

在这里插入图片描述
题目:
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)

1)创建一个和给定数组相同长度的新的数组profit,并将其中的元素全部初始化为0。
2) 从右向左遍历更新profit[i] 的值,使得其保存price[i…n-1] 中的最大利润值。
3) 从左向右遍历更新,使得其保存price[0,i ] 中的最大利润值
4) Return profit[n-1]

public int maxProfit(int[] prices)
	{
		if(prices.length>0)
		{

			   int[] profit=new int[prices.length];
			   
			    for (int i=0; i<profit.length; i++) 
			        profit[i] = 0; 
			  
			    int max_prices = prices[prices.length-1]; 
			    for (int i=prices.length-2;i>=0;i--) 
			    { 
			        if (prices[i] > max_prices) 
			            max_prices = prices[i]; 
			  
			        profit[i] = Math.max(profit[i+1], max_prices-prices[i]); 
			    } 

			    int min_prices = prices[0]; 
			    for (int i=1; i<prices.length; i++) 
			    { 

			        if (prices[i] < min_prices) 
			            min_prices = prices[i]; 
			  
			        profit[i] = Math.max(profit[i-1], profit[i] + 
			                                    (prices[i]-min_prices) ); 
			    } 
			    int result = profit[profit.length-1]; 

			  
			    return result; 
		}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凭栏听雨客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值