Array - 188. Best Time to Buy and Sell Stock IV
188. Best Time to Buy and Sell Stock IV
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 k transactions.
Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Example 1:
Input: [2,4,1], k = 2 Output: 2 Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.
Example 2:
Input: [3,2,6,5,0,3], k = 2 Output: 7 Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
思路:
如果会做123题,这一题就一定能想到这个最优解,也是动态规划,题目是允许交易k次,而123题是只允许两次。
代码:
java:
class Solution {
public int maxProfit(int k, int[] prices) {
int len = prices.length;
if (len == 0) return 0;
if (k >= len/2) return helper(prices);
int[] dp = new int[k+1];
int[] min = new int[k+1];
for (int i = 0; i <min.length; i++) {
min[i] = prices[0];
}
for (int i = 0; i < prices.length; i++) {
for (int j = 1; j <= k; j++) {
dp[j] = Math.max(dp[j], prices[i] - min[j]);
min[j] = Math.min(min[j], prices[i] - dp[j-1]);
}
}
return dp[k];
}
private int helper(int[] p) {
int len = p.length;
int res = 0;
for(int i = 1; i < len; i++) {
if (p[i] > p[i-1]) res += (p[i] - p[i-1]);
}
return res;
}
}
- [译]Laravel 5.0 之 Middleware (Filter-Style)
- [译]Laravel 5.0 之目录结构与命名空间
- Python机器学习的练习六:支持向量机
- [译]Laravel 5.0 之路由缓存
- [译]Laravel 5.0 之 表单验证类 (Form Requests)
- 如何在Python中保存ARIMA时间序列预测模型
- Laravel 5.0 发布, 海量新特性!!
- Python中的白噪声时间训练
- Python机器学习的练习五:神经网络
- 在Python中如何差分时间序列数据集
- 将Keras权值保存为动画视频,更好地了解模型是如何学习的
- TensorFlow:如何通过声音识别追踪蝙蝠
- Python机器学习的练习四:多元逻辑回归
- Python机器学习的练习三:逻辑回归
- 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 数组属性和方法
- 玩转dnmp之自定义容器
- python那些实用且不为人知的技巧
- 实现接口的契约测试
- java泛型总结
- 彻底搞懂 etcd 系列文章(九):etcd compact 和 watch API
- lru算法和redis的lru
- ThreadLocal
- 前端开发:font属性与font-variant如何使用?
- spring-boot使用aop进行多数据源切换
- CRC校验原来这么简单
- centos7安装kubernetes教程
- spring-boot自定义starter
- 实操 | kafka如何手动异步提交offset
- 解惑 | 为什么我根据时间戳获得的offset为空呢?
- spring-boot使用aop进行日志记录