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. new-nav-js

    'use strict';define([ 'jquery'], function($) { var nav = { init : function() { $("#burger-menu& ...

  2. OC基础--OC中类的声明与定义

    OC中设计一个类的步骤: 一.声明类: 1.用到的关键字--@interface 和 @end 2.类名 3.继承NSObject 4.属性 5.方法(行为,只需要声明) 二.实现(定义)类 1.用到 ...

  3. "use strict"

    "use strict";//严格模式 <!doctype html> <html> <head> <meta charset=" ...

  4. jQuery技术交流资料

    jQuery技术交流资料https://www.zybuluo.com/jikeytang/note/65371

  5. BIEEE 创建多维钻取分析(4)

    在上一节时,我们创建了一个基于部门号的工资分类汇总. 这里就引出了一个概念:维度 专业的解释大家自行百度,这里就不班门弄斧了.从数据的使用角度看,维度可以简单的理解成“数据分类汇总的一种依据”. 按“ ...

  6. 【codevs1200】 NOIP2012—同余方程

    codevs.cn/problem/1200/ (题目链接) 题意 求关于 x 的同余方程 ax ≡ 1 (mod b)的最小正整数解. Solution 这道题其实就是求${a~mod~b}$的逆元 ...

  7. [NOIP2011] 普及组

    数字反转 小模拟 #include<cstdio> #include<iostream> #include<cstring> using namespace std ...

  8. POJ 3273 Monthly Expense

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

  9. jquery------显示加载的js时出现中文乱码解决方法

    方法: 把my.js文件复制出来,用记事本打开,再另存为的时候设置编码格式为utf-8即可

  10. -----------------------------------项目中整理的非常有用的PHP函数库(二)-----------------------------------------------------

    6.PHP列出目录下的文件名 如果你想列出目录下的所有文件,使用以下代码即可: function listDirFiles($DirPath){ if($dir = opendir($DirPath) ...