码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode——Best Time to Buy and Sell Stock III

时间:2014-07-13 13:55:14      阅读:305      评论:0      收藏:0      [点我收藏+]

标签: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 at most two transactions.

Note:

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-iii/

题目:假设你有一个数组,其中的第 i 个元素代表给定的第 i 天的股票价格。

设计一个算法找出最大的利润。你可以完成最多两次交易。

思路:将数组分成前后两个区间,求出这两个区间的最大差值。

借鉴了网友的做法[1]。动态规划,用两个数组记录状态,f[i]表示区间[0,i](0<=i<=n-1) 的最大利润,g[i]表示区间[i,n-1](0<=i<=n-1) 的最大利润。

	public static int maxProfit(int[] prices) {
		if (prices.length < 2)
			return 0;
		int f[] = new int[prices.length];
		int g[] = new int[prices.length];
		for (int i = 1, valley = prices[0]; i < prices.length; ++i) {
			valley = Math.min(valley, prices[i]);
			f[i] = Math.max(f[i - 1], prices[i] - valley);
		}
		for (int i = prices.length - 2, peak = prices[prices.length - 1]; i >= 0; --i) {
			peak = Math.max(peak, prices[i]);
			g[i] = Math.max(g[i], peak - prices[i]);
		}
		int max_profit = 0;
		for (int i = 0; i < prices.length; ++i)
			max_profit = Math.max(max_profit, f[i] + g[i]);
		return max_profit;
	}

[1] http://www.cnblogs.com/apoptoxin/p/3770092.html



LeetCode——Best Time to Buy and Sell Stock III,布布扣,bubuko.com

LeetCode——Best Time to Buy and Sell Stock III

标签:leetcode

原文地址:http://blog.csdn.net/laozhaokun/article/details/37737175

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!