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 ...
随机推荐
- SSH框架总结(框架分析+环境搭建+实例源码下载)
来源于: http://blog.csdn.net/shan9liang/article/details/8803989 首先,SSH不是一个框架,而是多个框架(struts+spring+hiber ...
- Spring MVC框架
这个Spring Web MVC 框架提供了模型视图控制器的架构,这种结构能够被用来开发灵活的和松耦合的Web应用程序. 这种MVC模式能够将应用程序分离成不同的层面,(输入逻辑,业务逻辑,UI逻辑) ...
- 【HDU 2203】亲和串
题 题意 给你一个字符串s1,字符串s2,s1循环移位,使s2包含在s1中,则s2 是s1的亲和串 分析 把s1自身复制一遍接在后面. 方法一: 用strstr函数. 方法二: KMP算法. 方法三: ...
- POJ-1273 Drainage Ditches 最大流Dinic
Drainage Ditches Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 65146 Accepted: 25112 De ...
- Code Review Engine Learning
相关学习资料 https://www.owasp.org/index.php/Code_review https://www.owasp.org/images/8/8e/OWASP_Code_Revi ...
- 查看apk包名package和入口activity名称的方法
ctrl+r 打开CMD窗口 进入sdk-aapt目录 执行命令:aapt dump badging xx.apk 内容太多?不好看,没关系,全部拷出来,ctrl+f,so easy! package ...
- MySQL学习笔记01-MYSQL安装
一 MySQL简介 MySQL是一个关系型数据库管理系统,由瑞典 MySQL AB 公司开发,目前属于 Oracle 公司. MySQL 最流行的关系型数据库管理系统. MySQL分为企业版和社区版. ...
- 伪分布模式下执行wordcount实例时报错解决办法
问题1.不能分配内存,错误提示如下: FAILEDjava.lang.RuntimeException: Error while running command to get file permiss ...
- pthread_rwlock
读写锁 1.概述 读写锁与互斥量类似,不过读写锁允许更高的并行性.互斥量要么是锁住状态,要么是不加锁状态,而且一次只有一个线程对其加锁.读写锁可以有三种状态:读模式下加锁状态,写模式下加锁状态,不 ...
- get_magic_quotes_gpc函数
magic_quotes_gpc函数在php中的作用是判断解析用户提示的数据,如包括有:post.get.cookie过来的数据增加转义字符“\”,以确保这些数据不会引起程序,特别是数据库语句因为特殊 ...