OJ4121 and OJ2968-股票买卖 and Maximun sum【各种dp之6 and 9】
2017-12-30 08:09
281 查看
股票买卖
题目
阿福该炒股了,然后假设他已经预测到了后几天的股票,要求他最多买卖两次的赚到的最大值。(注:他只有第一次卖了才能再买)
输入
37
5 14 -2 4 9 3 17
6
6 8 7 4 1 -2
4
18 9 5 2
输出
282
0
解题思路
用f[i]表示从1到i天买一次的最优解,fm[i]表示从第i天到第n天买一次的最优解,然后枚举一下咯(是的吧)。代码
#include<cstdio> #include<iostream> #include<cstring> using namespace std; int t,a[100001],maxs,n,min1,max1,min2,max2; int fm[100001],f[100001]; int main() { scanf("%d",&t); for (int ti=1;ti<=t;ti++) { memset(f,0,sizeof(f)); memset(fm,0,sizeof(fm)); //清零 maxs=0; scanf("%d",&n); for (int i=1;i<=n;i++) { scanf("%d",&a[i]); } maxs=a ; for (int i=n-1;i>=1;i--) { maxs=max(a[i],maxs); f[i]=max(maxs-a[i],f[i+1]); }//求f maxs=a[1]; for (int i=2;i<=n;i++) { maxs=min(a[i],maxs); fm[i]=max(a[i]-maxs,fm[i-1]); }//求fm maxs=0; for (int i=2;i<n;i++) { maxs=max(f[i]+fm[i],maxs); }//求最大值 printf("%d\n",max(a[2]-a[1],maxs)); } }
Maximum sum
题目
求两个不重复的子段和,让他最大输入
110
1 -1 2 2 3 -3 4 -4 5 -5
输出
13解题思路
同上用f[i]表示从1到i个的最大子段和,fm[i]表示从第i个到第n个的最大子段和,然后枚举一下咯(是的吧)。
代码
#include<cstdio> #include<iostream> #include<cstring> using namespace std; int t,n,mins,f[50002],s[50002],fm[50002],a[50002]; int main() { < b3ef span class="hljs-built_in">scanf("%d",&t); for (int ti=1;ti<=t;ti++) { memset(f,0,sizeof(f)); memset(fm,0,sizeof(fm)); memset(s,0,sizeof(s)); scanf("%d",&n); for (int i=1;i<=n;i++) { scanf("%d",&a[i]); s[i]=s[i-1]+a[i]; } f[1]=a[1];mins=min(s[1],0); for (int i=2;i<=n;i++) { f[i]=max(fm[i-1],s[i]-mins); mins=min(s[i],mins); }//求f for (int i=n;i>=1;i--) { s[i]=s[i+1]+a[i]; } fm =a ;mins=min(s ,0); for (int i=n-1;i>=1;i--) { fm[i]=max(fm[i+1],s[i]-mins); mins=min(s[i],mins); }//求fm mins=-23333333; for (int i=1;i<n;i++) { mins=max(mins,f[i]+fm[i+1]); }//求最大值 printf("%d\n",mins); } }
相关文章推荐
- Best Time to Buy and Sell Stock II DP买卖股票
- LeetCode Best Time to Buy and Sell Stock 买卖股票的最佳时机 (DP)
- 【LintCode】 Best Time to Buy and Sell Stock III 买卖股票的最佳时机 III
- 121. Best Time to Buy and Sell Stock 最佳买卖股票时间
- Leetcode 121 Best Time to Buy and Sell Stock 单次买卖股票最大收益
- 九度 1537:买卖股票(区间DP)
- 122. Best Time to Buy and Sell Stock II 最佳买卖股票的时间
- LintCode--best-time-to-buy-and-sell-stock(买卖股票的最佳时机)
- LeetCode:Best Time to Buy and Sell Stock(买卖股票)系列
- LeetCode——Best Time to Buy and Sell Stock II (股票买卖时机问题2)
- LeetCode题库解答与分析——#121. 买卖股票的最佳时机BestTimeToBuyAndSellStock
- [各种面试题] 买卖股票最多K次
- [leetcode 121] Best Time to Buy and Sell Stock---只能买卖股票一次的最大收益
- LintCode--best-time-to-buy-and-sell-stock-ii(买卖股票的最佳时机 II)
- array-股票买卖问题--- Best Time to Buy and Sell Stock
- (LeetCode)Best Time to Buy and Sell Stock -- 求股票买卖的最大利润
- leetcode——Best Time to Buy and Sell Stock III 买卖股票最大收益(AC)
- [LeetCode] 121. Best Time to Buy and Sell Stock 买卖股票的最佳时间
- 【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】
- LeetCode OJ:Best Time to Buy and Sell Stock(股票买卖的最佳时期)