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

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

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.

Note:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

1 class Solution { 2 public: 3     int maxProfit(vector
&prices) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if (prices.size() == 0) 7 return 0; 8 9 vector
f1(prices.size());10 vector
f2(prices.size());11 12 int minV = prices[0];13 f1[0] = 0;14 for(int i = 1; i < prices.size(); i++)15 {16 minV = min(minV, prices[i]);17 f1[i] = max(f1[i-1], prices[i] - minV);18 }19 20 int maxV = prices[prices.size()-1];21 f2[f2.size()-1] = 0;22 for(int i = prices.size() - 2; i >= 0; i--)23 {24 maxV = max(prices[i], maxV);25 f2[i] = max(f2[i+1], maxV - prices[i]);26 }27 28 int sum = 0;29 for(int i = 0; i < prices.size(); i++)30 sum = max(sum, f1[i] + f2[i]);31 32 return sum;33 }34 };

转载于:https://www.cnblogs.com/chkkch/archive/2012/11/29/2795178.html

你可能感兴趣的文章
linux命令之ifconfig详细解释
查看>>
NAT地址转换
查看>>
Nhibernate 过长的字符串报错 dehydration property
查看>>
Deque - leetcode 【双端队列】
查看>>
gulp插件gulp-ruby-sass和livereload插件
查看>>
免费的大数据学习资料,这一份就足够
查看>>
clientWidth、clientHeight、offsetWidth、offsetHeight以及scrollWidth、scrollHeight
查看>>
企业级应用与互联网应用的区别
查看>>
itext jsp页面打印
查看>>
Perl正则表达式匹配
查看>>
DB Change
查看>>
nginx --rhel6.5
查看>>
Eclipse Python插件 PyDev
查看>>
selenium+python3模拟键盘实现粘贴、复制
查看>>
第一篇博客
查看>>
typeof与instanceof的区别
查看>>
网站搭建(一)
查看>>
SDWebImage源码解读之SDWebImageDownloaderOperation
查看>>
elastaticsearch
查看>>
postgreSQL 简单命令操作
查看>>