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的更多相关文章

  1. 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- ...

  2. 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 ...

  3. 【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 ...

  4. 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 ...

  5. 【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 ...

  6. 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 ...

  7. [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 ...

  8. 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 ...

  9. 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 ...

随机推荐

  1. 【转载】Velocity模板引擎的介绍和基本的模板语言语法使用

    原文地址http://www.itzhai.com/the-introduction-of-the-velocity-template-engine-template-language-syntax- ...

  2. [转]JVM 内存初学 (堆(heap)、栈(stack)和方法区(method) )

    这两天看了一下深入浅出JVM这本书,推荐给高级的java程序员去看,对你了解JAVA的底层和运行机制有比较大的帮助.废话不想讲了.入主题: 先了解具体的概念:JAVA的JVM的内存可分为3个区:堆(h ...

  3. Vijos p1770 大内密探 树形DP+计数

    4天终于做出来了,没错我就是这么蒟蒻.教训还是很多的. 建议大家以后编树形DP不要用记忆化搜索,回溯转移状态个人感觉更有条理性. 大神题解传送门 by iwtwiioi 我的题解大家可以看注释&quo ...

  4. 使用FMDB事务批量更新数据库

    今天比较闲看到大家在群里讨论关于数据库操作的问题,其中谈到了“事务”这个词,坦白讲虽然作为计算机专业的学生,在上学的时候确实知道存储过程.触发器.事务等等这些名词的概念,但是由于毕业后从事的不是服务器 ...

  5. [NOIP2009] 提高组 洛谷P1071 潜伏者

    题目描述 R 国和 S 国正陷入战火之中,双方都互派间谍,潜入对方内部,伺机行动.历尽艰险后,潜伏于 S 国的 R 国间谍小 C 终于摸清了 S 国军用密码的编码规则: 1. S 国军方内部欲发送的原 ...

  6. java 中LinkedList的学习

    Java中,所有链表实际上都是双向链表的,即每个结点还存放在着指向前驱结点的引用. LinkedList中的contains方法检测某个元素是否出现在链表中. LinkedList类提供了一个用来访问 ...

  7. POJ 3273 Monthly Expense

    传送门 Time Limit: 2000MS Memory Limit: 65536K Description Farmer John is an astounding accounting wiza ...

  8. 用VSCode写python的正确姿势

    最近在学习python,之前一直用notepad++作为编辑器,偶然发现了VScode便被它的颜值吸引.用过之后发现它启动快速,插件丰富,下载安装后几乎不用怎么配置就可以直接使用,而且还支持markd ...

  9. swift项目中引入OC框架

  10. pthread_cancel

    #include <pthread.h> #include <stdio.h> #include<stdlib.h> #include <unistd.h&g ...