12.3 Best Time to Buy and Sell Stock
来源:互联网 发布:junos pulse mac 下载 编辑:程序博客网 时间:2024/05/20 05:24
Link: https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
I have no idea how to do this.Correct thought:
- This Q is equivalent to "Find i and j that maximizes Aj – Ai, where i < j."
- The simplest solution is O(n^2). http://leetcode.com/2010/11/best-time-to-buy-and-sell-stock.html
设dp[i]是[0,1,2...i]区间的最大利润,则该问题的一维动态规划方程如下
dp[i+1] = max{dp[i], prices[i+1] - minPrice}
minPrice是区间[0,1,2...,i]内的最低价格。我们要求解的最大利润 = max{dp[0], dp[1], dp[2], ..., dp[n-1]}
在实际写程序的时候,不需要构造数组,只用一个变量maxProfit,在循环中更新它就可以了。public class Solution { //DP public int maxProfit(int[] prices) { if(prices.length < 1) return 0; int minPrice = prices[0]; int maxProfit = 0; for(int i = 1; i < prices.length; i++){ maxProfit = Math.max(maxProfit, prices[i] - minPrice); minPrice = Math.min(minPrice, prices[i]); } return maxProfit; }}
Approach II: 差分序列 http://www.cnblogs.com/TenosDoIt/p/3436457.html
Time: O(n), Space: O(1)
把原始价格序列变成差分序列: prices[1]-prices[0], prices[2]-prices[1], ..., prices[n-1]-prices[n-2]。则要求最大利润prices[j]-prices[i],即求差分序列的最大子段和。因为:
prices[j]-prices[i]= (prices[j]-prices[j-1]) + (prices[j-1]-prices[j-2]) +...+ (prices[i+1]-prices[i])
public class Solution { //p[j]-p[i] = (p[j]-p[j-1]) + (p[j-1]-p[j-2])+...+(p[i+1]-p[i]) public int maxProfit(int[] prices) { if(prices.length <=1) return 0; int profit = 0; int curSum = 0; for(int i = 0; i < prices.length-1; i++){ if(curSum < 0){ curSum = prices[i+1] - prices[i]; } else{ curSum += prices[i+1] - prices[i]; } if(curSum > profit){ profit = curSum; } } return profit; }}
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time To Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- UVa1213 Sum of Different Primes
- opencv学习_11 (模板匹配(包括单模板和多模板))
- HDU 1505:City Game(悬线DP)
- ubuntu 安装ftp服务器
- poj 1111 Image Perimeters DFS
- 12.3 Best Time to Buy and Sell Stock
- K-mean and fuzzy C-mean clustering
- FPGA综合优化
- 什么是Spring, 它有什么特点?
- poj 3190Stall Reservations
- st link
- VC++6.0 调试方式
- 拦截导弹
- HDU 4405 - Aeroplane chess (概率DP 求期望)