博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode]Best Time to Buy and Sell Stock III
阅读量:4150 次
发布时间:2019-05-25

本文共 1189 字,大约阅读时间需要 3 分钟。

class Solution {//Let f[i][j] to be the maximum sum of j segments from the first i numbers, where the last element we choose is a[i]. //We have two strategies to achieve it:////1.Choosing the optimal j-1 segments from the first k numbers, and starting a new segment with a[i]://f[i][j] = f[k][j-1] + a[i], where j-1 <= k <= i-1.//let g[j-1] = max(f[k][j-1])//2.Appending a[i] to the last segment in the first i-1 numbers//f[i][j] = f[i-1][j] + a[i].public:	int getMaxProfitDP(vector
&prices, int transNum) { vector
f(transNum+1, 0); vector
g(transNum+1, 0); for (int i = 1; i < prices.size(); ++i) { int diff = prices[i]-prices[i-1]; int m = min(i, transNum);//if not enough to complete transNum transactions for (int j = m; j >= 1; --j) {//why scan m->1, because we can not //let cur diff accumulate, note: g[j-1] f[j] = max(f[j], g[j-1])+diff;//1.g[j-1] starting a new segment and 2.f[j] Appending a[i] to the last segment g[j] = max(g[j], f[j]);//record } } int ans = 0; for(int i = 1; i <= transNum; ++i) ans = max(ans, g[i]); return ans; } int maxProfit(vector
&prices) { return getMaxProfitDP(prices, 2); }};

转载地址:http://yoxti.baihongyu.com/

你可能感兴趣的文章
openlayers安装引用
查看>>
js报错显示subString/subStr is not a function
查看>>
高德地图js API实现鼠标悬浮于点标记时弹出信息窗体显示详情,点击点标记放大地图操作
查看>>
初始化VUE项目报错
查看>>
vue项目使用安装sass
查看>>
在osg场景中使用GLSL语言——一个例子
查看>>
laravel 修改api返回默认的异常处理
查看>>
laravel事务
查看>>
【JavaScript 教程】浏览器—History 对象
查看>>
这才是学习Vite2的正确姿势!
查看>>
7 个适用于所有前端开发人员的很棒API,你需要了解一下
查看>>
49个在工作中常用且容易遗忘的CSS样式清单整理
查看>>
20种在学习编程的同时也可以在线赚钱的方法
查看>>
隐藏搜索框:CSS 动画正反向序列
查看>>
【视频教程】Javascript ES6 教程27—ES6 构建一个Promise
查看>>
【5分钟代码练习】01—导航栏鼠标悬停效果的实现
查看>>
127个超级实用的JavaScript 代码片段,你千万要收藏好(中)
查看>>
127个超级实用的JavaScript 代码片段,你千万要收藏好(下)
查看>>
【web素材】03-24款后台管理系统网站模板
查看>>
Flex 布局教程:语法篇
查看>>