Best Time to Buy and Sell Stock
来源:互联网 发布:软件著作权 硬件环境 编辑:程序博客网 时间:2024/05/16 15:50
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
只做一次交易:
贪心算法(最小买进,最大卖出,卖出时间比买进时间大):
int maxProfit(vector<int> &prices) { if(prices.size()<2) return 0; int min_cur =prices[0],profit =0; for(int i=1;i<prices.size();i++) { if(prices[i]-min_cur>profit) { profit =prices[i]-min_cur; } min_cur =min(prices[i],min_cur); } return profit; }
Best Time to Buy and Sell Stock II Total Accepted: 20291 Total Submissions: 55090 My Submissions
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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
int maxProfit(vector<int> &prices) { int sum =0; for(int i=1;i<prices.size();i++){ int diff =prices[i] -prices[i-1]; if(diff>0) sum+=diff; } return sum; }
Best Time to Buy and Sell Stock III
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).
最多两次交易
int valley,peak; int maxProfit(vector<int> &prices) { if(prices.size()<2)return 0; const int n=prices.size(); vector<int> f(n,0); vector<int> g(n,0); for(int i=1,valley =prices[0];i<n;i++) { valley =min(valley,prices[i]); f[i] =max(f[i-1],prices[i] -valley); } for(int i=n-2,peak=prices[n-1];i>=0;--i) { peak =max(peak,prices[i]); g[i] =max(g[i],peak -prices[i]); } int max_profit =0; for(int i=0;i<n;++i) { max_profit =max(max_profit,f[i]+g[i]); } return max_profit; }};
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time To Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- hbase基础整理
- C++ sizeof之虚继承
- C++中的空类,默认产生哪些类成员函数?
- php中global与$GLOBAL的用法及区别
- 日期
- Best Time to Buy and Sell Stock
- 怎样使一个Android应用不被杀死?(整理)
- 个人开发经验总结
- 删除word中的回车符
- MySQL数据库最优化的简单方法
- Cocos2dx游戏源码合集
- JAVA for语句中的break、continue、return使用简介
- js中obj.style后面的属性如果有下划线换换成大写字母
- FusionCharts绘制图形报表