Best Time to Buy and Sell Stock | & || & III
Best Time to Buy and Sell Stock I
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.
Example
Given array [3,2,3,1,2]
, return 1
.
分析:因为卖出总是在买入后,所以,只要有更低的买入价格,我们就可以更新买入价格,如果价格比买入价格低,我们就更新tempMax。看代码后即可明白。
public class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length <= ) return ; int tempMax = ;
int buyPrice = prices[]; for (int i = ; i < prices.length; i++) {
if (prices[i] > buyPrice) {
tempMax = Math.max(tempMax, prices[i] - buyPrice);
} else {
buyPrice = prices[i];
}
}
return tempMax;
}
}
Best Time to Buy and Sell Stock II
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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Example
Given an example [2,1,2,0,1], return 2
分析:既然允许unlimited 交易,那么,每个价格波峰都是卖出点,每个价格波谷都是买入点。
public class Solution {
public int maxProfit(int[] prices) {
// corner cases
if (prices == null || prices.length <= ) return ;
int buyPrice = prices[], totalProfit = ; for (int i = ; i < prices.length; i++) {
if (prices[i] < prices[i - ]) {
totalProfit += prices[i - ] - buyPrice;
buyPrice = prices[i];
}
} totalProfit += prices[prices.length - ] - buyPrice;
return totalProfit;
}
}
public class Solution {
public int maxProfit(int[] prices) {
return maxProfit(prices, );
} public int maxProfit(int[] prices, int fee) {
if (prices.length <= ) return ;
int days = prices.length;
int[] buy = new int[days];
int[] sell = new int[days]; buy[] = -prices[] - fee;
for (int i = ; i< days; i++) {
// keep the same as day i-1, or buy from sell status at day i-1
buy[i] = Math.max(buy[i - ], sell[i - ] - prices[i] - fee);
// keep the same as day i-1, or sell from buy status at day i-1
sell[i] = Math.max(sell[i - ], buy[i - ] + prices[i]);
}
return sell[days - ];
}
}
Best Time to Buy and Sell Stock III
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.
Example
Given an example prices = [4,4,6,1,1,4,2,5]
, return 6
.
分析:
既然题目说,最多只能交易两次,所以,可能是一次,也可能是两次。如果是只交易一次,那么我们就从开始点(0)到结束点(prices.length - 1) 找出只做一次交易的maxProfit. 如果只做两次,那么两次只能在 (0, k) 和 (k + 1, prices.length - 1) 产生,而k的范围是 0 <= k <= prices.length - 1.
class Solution {
/**
* @param prices: Given an integer array
* @return: Maximum profit
* cnblogs.com/beiyeqingteng/
*/
public int maxProfit(int[] prices) {
if (prices == null || prices.length <= ) return ; int max = ;
for (int i = ; i < prices.length; i++) {
if (i == prices.length - ) {
max = Math.max(max, maxProfit(prices, , i));
} else {
max = Math.max(max, maxProfit(prices, , i) + maxProfit(prices, i + , prices.length - ));
}
}
return max;
} // once one transaction is allowed from point i to j
private int maxProfit(int[] prices, int i, int j) {
if (i >= j) return ;
int profit = ; int lowestPrice = prices[i]; for (int k = i + ; k <= j; k++) {
if (prices[k] > lowestPrice) {
profit = Math.max(profit, prices[k] - lowestPrice);
} else {
lowestPrice = prices[k];
}
}
return profit;
}
};
另一种方法,直接倒过来,考虑从当前到最后一天能够只做一次交易的时候,能够获取的最大利益。这种情况下,我们要找到最大的sellPrice.
public class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length <= ) return ; int max = ;
int[] maxProfit = maxProfitForward(prices);
int[] maxLoss = maxProfitBackward(prices); for (int i = ; i < prices.length; i++) {
if (i == prices.length - ) {
max = Math.max(max, maxProfit[i]);
} else if (i == ) {
max = Math.max(max, maxLoss[i]);
} else {
max = Math.max(max, maxProfit[i] + maxLoss[i]);
}
}
return max;
} // once one transaction is allowed from point i to j
private int[] maxProfitBackward(int[] prices) {
int sellPrice = prices[prices.length - ];
int[] maxLoss = new int[prices.length];
int tempMin = ; for (int i = prices.length - ; i >= ; i--) {
if (prices[i] < sellPrice) {
tempMin = Math.max(tempMin, sellPrice - prices[i]);
} else {
sellPrice = prices[i];
}
maxLoss[i] = tempMin;
}
return maxLoss;
} private int[] maxProfitForward(int[] prices) {
int buyPrice = prices[];
int[] maxProfit = new int[prices.length];
int tempMax = ; for (int i = ; i < prices.length; i++) {
if (prices[i] > buyPrice) {
tempMax = Math.max(tempMax, prices[i] - buyPrice);
} else {
buyPrice = prices[i];
}
maxProfit[i] = tempMax;
}
return maxProfit;
}
}
Best Time to Buy and Sell Stock IV
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 k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
第一种方法:暴力解法
因为最多可以交易 k 次,在prices array里,我们总能够找到一个点 p, 从p + 1 到 prices array的最后一个元素,最多交易次数为1, 那么我们就可以递归调用原函数。
public class Solution {
public int maxProfit(int k, int[] prices) {
return helper(k, prices, , prices.length - );
} private int helper(int k, int[] prices, int start, int end) {
if (start >= end || k == ) return ;
if (k == ) {
int buyPrice = prices[start];
int maxProfit = ;
for (int i = start + ; i <= end; i++) {
if (prices[i] > buyPrice) {
maxProfit = Math.max(maxProfit, prices[i] - buyPrice);
} else {
buyPrice = prices[i];
}
}
return maxProfit;
} else {
int max = ;
for (int p = start; p <= end; p++) {
max = Math.max(max, helper(k - , prices, start, p) + helper(, prices, p + , end));
}
return max;
}
}
}
Best Time to Buy and Sell Stock | & || & III的更多相关文章
- 27. Best Time to Buy and Sell Stock && Best Time to Buy and Sell Stock II && Best Time to Buy and Sell Stock III
Best Time to Buy and Sell Stock (onlineJudge: https://oj.leetcode.com/problems/best-time-to-buy-and- ...
- LeetCode 笔记23 Best Time to Buy and Sell Stock III
Best Time to Buy and Sell Stock III Say you have an array for which the ith element is the price of ...
- 【leetcode】Best Time to Buy and Sell Stock III
Best Time to Buy and Sell Stock III Say you have an array for which the ith element is the price of ...
- LeerCode 123 Best Time to Buy and Sell Stock III之O(n)解法
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...
- 【leetcode】123. Best Time to Buy and Sell Stock III
@requires_authorization @author johnsondu @create_time 2015.7.22 19:04 @url [Best Time to Buy and Se ...
- LeetCode: Best Time to Buy and Sell Stock III 解题报告
Best Time to Buy and Sell Stock IIIQuestion SolutionSay you have an array for which the ith element ...
- [leetcode]123. Best Time to Buy and Sell Stock III 最佳炒股时机之三
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...
- LN : leetcode 123 Best Time to Buy and Sell Stock III
lc 123 Best Time to Buy and Sell Stock III 123 Best Time to Buy and Sell Stock III Say you have an a ...
- Leetcode之动态规划(DP)专题-123. 买卖股票的最佳时机 III(Best Time to Buy and Sell Stock III)
Leetcode之动态规划(DP)专题-123. 买卖股票的最佳时机 III(Best Time to Buy and Sell Stock III) 股票问题: 121. 买卖股票的最佳时机 122 ...
随机推荐
- 利用less监视模式实时预览样式刷新浏览器
[前言]此处介绍的方法只是我个人的用法,相信大家有更好更简洁的方式. 上次写到利用LiveReload解放F5.而且LiveReload可以编辑sass/less/stylus.但是可惜发现LiveR ...
- 什么是谷歌loon计划
互联网服务已经与人类的生活密不可分,但受地理环境限制,目前全球只有三分之一的幸运儿能够体验到这种服务.为了让更多的人感受互联网,Google推出了一项名为“Project Loon”的计划,利用氢气球 ...
- load and initialize
NSObject是一切OC类的基类,所以我们必须对NSObject所有的方法有一个清楚的认识. + (void)load; 当类或者分类被加入到runtime时,load方法会被调用,也就是说在mai ...
- GPUImage学习
1.GLProgram--加载vertex和fragment的shader. 好处是完全将shader模块的加载过程独立出来. 学习:每个函数处理一件事,且函数的粒度刚好 在glLinkProgram ...
- Windows下python的配置
Windows下python的配置 希望这是最后一次写关于python的配置博客了,已经被python的安装烦的不行了.一开始我希望安装python.手动配置pip并使用pip安装numpy,然而发现 ...
- 【BZOJ-2223】PATULJCI 可持久化线段树
2223: [Coci 2009]PATULJCI Time Limit: 10 Sec Memory Limit: 259 MBSubmit: 728 Solved: 292[Submit][S ...
- codevs1322 单词矩阵
题目描述 Description 对于包含字母A到Y各一次的单词S,将其从上到下从左到右写在一个5*5的矩阵中,如单词ADJPTBEKQUCGLRVFINSWHMOXY写出来如下: A D J P T ...
- 2016年4月7日 js的全选和反选
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title> ...
- xcode6.3插件失效
1.打开终端,输入以下代码:defaults read /Applications/Xcode.app/Contents/Info DVTPlugInCompatibilityUUID 2.获取到DV ...
- iOS 刚刚,几分钟前,几小时前,几天前,几月前,几年前
- (NSString *)compareCurrentTime:(NSDate*) compareDate { NSTimeInterval timeInterval = [compareDate ...