Array - 123. Best Time to Buy and Sell Stock III
123. Best Time to Buy and Sell Stock III
Say you have an array for which the _i_th 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.
**Note: **You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Input: [3,3,5,0,0,3,1,4] Output: 6 Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Example 2:
Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.
思路:
这一题也是买卖股票的问题,条件是允许买卖两次,最直接的办法是在121的基础上,分为两次最大盈利做。这里只说一下动态规划来解。
代码:
java:
class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) return 0;
int[] dp = new int[3];
int[] min = new int[]{prices[0], prices[0], prices[0]};
for (int i = 0; i < prices.length; i++) {
for (int k = 1; k <= 2; k++) {
dp[k] = Math.max(dp[k], prices[i] - min[k]);
min[k] = Math.min(min[k], prices[i] - dp[k-1]);
}
}
return dp[2];
}
}
- RegQueryValueEx正确使用方法
- 区块链+医疗五类应用前景广阔,英美已有企业试水
- Linux进程关系
- 基于OBS的插件开发总结
- Linux从程序到进程
- asp.net 解码gb2312下urlencode后的字符串
- XCode日常使用备忘录
- .net中close和dispose及关闭流操作
- Linux文件管理相关命令
- 实现滑动分页(微博分页方式)
- 腾讯汇赢正式上线,变革2018大连房地产市场营销
- Windows下程序启动时出现0xc000007b错误的解决方案
- 外媒报道:CBM.com、NMA.com等域名齐交易
- ObjectDataSource与GridView配合使用经验总结系列一:数据绑定
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- 【C语言简单说】二:第一个C语言程序详解(3)
- 【C语言简单说】三:整数变量和输出扩展(1)
- 【C语言简单说】三:整数变量和输出扩展(2)
- 【C语言简单说】三:整数变量扩展和输出扩展(3)
- 【C语言简单说】三:浮点数变量和字符变量(4)
- 【C语言简单说】三:变量总结ASCII码扩展(5)
- 【C语言简单说】四:常量
- 【C语言简单说】五:常用运算符
- 【C语言简单说】六:取模运算符以及变量的扩展
- 【C语言简单说】七:自定义函数(1)
- 【C语言简单说】七:自定义函数(2)
- 【C语言简单说】七:自定义函数(3)
- 【C语言简单说】八:分支结构之if(1)
- 【C语言简单说】八:分支结构之if...else...(2)
- 【C语言简单说】八:分支结构之if...else if()...else...(3)