LeetCode——Best Time to Buy and Sell Stock III
来源:互联网 发布:君理资本 知乎 编辑:程序博客网 时间:2024/06/09 17:45
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
0 0
- LeetCode123—Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock III
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- leetcode 62: Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- 【leetcode】Best Time to Buy and Sell Stock III
- LeetCode - Best Time to Buy and Sell Stock III
- LeetCode之Best Time to Buy and Sell Stock III
- [LeetCode]Best Time to Buy and Sell Stock III
- LeetCode: Best Time to Buy and Sell Stock III
- [Leetcode]Best Time to Buy and Sell Stock III
- [leetcode]Best Time to Buy and Sell Stock III
- leetcode题目:Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- linux 命令之ifconfig详解
- 【翻译自mos文章】 11gR1版本 asmcmd的新命令--cp、md_backup、md_restore
- 信号量机制中的DOWN操作与UP操作详解
- 正则表达式验证日期
- ORA-00603错误
- LeetCode——Best Time to Buy and Sell Stock III
- 我现在的梦想
- Android.mk
- 山天大畜
- LeetCode OJ : Median of Two Sorted Arrays
- 两道中等贪心题,poj 3040, poj 3190
- opengl 中的光照与颜色 转载
- 面试的知识(收集)
- 程序员的八种级别