【LeetCode】Best Time to Buy and Sell Stock III
来源:互联网 发布:淘宝上的百乐笔有假吗 编辑:程序博客网 时间:2024/06/07 09:31
Say you have an array for which the ith element is the price of a given stock on dayi.
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).
思路:这个题目只要是从第0个到第n-1个元素进行分割,对前后部分分别求出最大收益,相加然后比较得到最大值。
class Solution {public:int maxProfit(vector<int> &prices) { int size=prices.size(); if(size<=1)return 0; vector<int> f1(size); vector<int> f2(size); int minv=prices[0]; for(int i=1;i<size;i++){ minv=std::min(minv,prices[i]); f1[i]=std::max(f1[i-1],prices[i]-minv); } int maxv=prices[size-1]; f2[size-1]=0; for(int i=size-2;i>=0;i--){ maxv=std::max(maxv,prices[i]); f2[i]=std::max(f2[i+1],maxv-prices[i]); } int sum=0; for(int i=0;i<size;i++){ sum=std::max(sum,f1[i]+f2[i]); } return sum;}};
0 0
- LeetCode Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock III
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- leetcode 62: Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- 【leetcode】Best Time to Buy and Sell Stock III
- LeetCode - Best Time to Buy and Sell Stock III
- LeetCode之Best Time to Buy and Sell Stock III
- [LeetCode]Best Time to Buy and Sell Stock III
- LeetCode: Best Time to Buy and Sell Stock III
- [Leetcode]Best Time to Buy and Sell Stock III
- [leetcode]Best Time to Buy and Sell Stock III
- leetcode题目:Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- LeetCode-Best Time to Buy and Sell Stock III
- Discuz升级提示static/image/postbg/3.jpg下载出现问题的解决办法
- struts2拦截器的使用
- linux dpm机制分析(下)
- SpringMVC处理流程
- 西游记 第一章 Linux的启程
- 【LeetCode】Best Time to Buy and Sell Stock III
- 一次函数默认值带来的问题
- 使用Spring邮件发送Email
- UVALive 3641 Leonardo's Notebook (置换)
- js select 循环
- 430编程C语言常识(IAR)结构体与联合体
- Ustc-1280 Finding shortest path 网络流
- Cocos2dx 3.0 过渡篇(二十四)死不了的贪食蛇(重力版)
- php 面向对象