Best time to buy and sell stock--LeetCode
来源:互联网 发布:php ext目录 编辑:程序博客网 时间:2024/05/22 19:45
题目:
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.
思路:可以看成是一个典型的DP问题,根据给出的股票每天的价格,算出当天与前一天之间的盈亏。然后求出此数组的最大子数组和
其实也可以在n^2的时间内解决问题,在某一天卖出,在以后的任何一天卖出,计算出最大的盈利。没有空间复杂度。
#include <iostream>#include <vector> #include <string>using namespace std;int BestTimeToSell(vector<int>& vec){vector<int> share(vec.size(),0);int i;for(i=1;i<vec.size();i++)share[i] = vec[i]-vec[i-1];int sum=share[0];int cur =share[0];for(i=1;i<share.size();i++){if(cur < 0)cur = share[i];elsecur += share[i];if(cur > sum )sum = cur;}return sum < 0? 0:sum;}int main(){int array[]={12,8,10,6,15,18,10};vector<int> vec(array,array+sizeof(array)/sizeof(int));cout<<BestTimeToSell(vec);return 0;}
上述方法是讲一个问题转化为另一个问题,其实也可以不使用数组就可以解决问题。使用用“局部最优和全局最优解法”。思路是维护两个变量,一个是到目前为止最好的交易,另一个是在当前一天卖出的最佳交易(也就是局部最优)。递推式是local[i+1]=max(local[i]+prices[i+1]-price[i],0), global[i+1]=max(local[i+1],global[i])。这样一次扫描就可以得到结果,时间复杂度是O(n)。而空间只需要两个变量,即O(1)。代码如下:
int maxProfit(int[] prices) { if(prices==null || prices.length==0) return 0; int local = 0; int global = 0; for(int i=0;i<prices.length-1;i++) { local = Math.max(local+prices[i+1]-prices[i],0); global = Math.max(local, global); } return global; }
1 0
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock
- LeetCode Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- Leetcode: Best time to buy and sell a stock I
- Leetcode: Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock
- [Leetcode] Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock III
- LeetCode : Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock
- [JAVA]LeetCode105 Construct Binary Tree from Preorder and Inorder Traversal
- 调用微信聊天功能和分享功能
- 约瑟夫环问题
- Android软件自动更新,通知栏显示,项目源码
- 工作学习中遇到的最好的工具推荐
- Best time to buy and sell stock--LeetCode
- C#连接SQL Server数据库
- 【SICP练习】139 练习3.70
- Auto Layout Guide——基于苹果开发者文档
- 第四周阅读程序4
- css3的box-sizing
- oracle伪列rownum
- Advanced FAQ System For OpenCart 2.x
- tomcat https