首页 > 代码库 > Best Time to Buy and Sell Stock(动态规划)
Best Time to Buy and Sell Stock(动态规划)
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.
思路:变相的求最大子数组,是算法导论上的例题,书上用分治法做的。
若prices=[1,4,2,8,1],每两数相减所得的利润,即头一天买入,第二天卖出。
profit=[0,3,-2,6,-7],可以看到第一天买入,最后一天卖出的profit为3+(-2)+6+(-7)=0
代码:
class Solution {public: int maxProfit(vector<int> &prices) { int len=prices.size(); int res=0; int temp=0; if(len==0) return res; vector<int> profit(len,0); vector<int> dp(len,0); for(int i=0;i<len;++i){ if(i==0) {profit[i]=0;continue;} profit[i]=prices[i]-prices[i-1]; } dp[0]=profit[0]; for(int i=1;i<len;++i){ dp[i]=max(dp[i-1]+profit[i],profit[i]); if(dp[i]>res) res=dp[i]; } return res; }};
Best Time to Buy and Sell Stock(动态规划)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。