leetcode_121题——Best Time to Buy and Sell Stock(动态规划)
2015-05-18 22:24
627 查看
这道题是已知一些天的股价,需要选定一天买进和一天卖出,得到最大值,可以采用类似于动态规划的做法
从后往前遍历,同时记录后面的最大股价,和当前这个点买进时的最大收益,与之前的最大收益取个最大值
依次往前递推即可
下面是AC的算法
这道题的动态规划的思想在于,子问题分解为这个点买进时的收益与后面所有的买进时的收益的最大值之间选一个
依次往前即可,就成为一个线性求解的问题,
需要注意的是在这个题中也可以选择不买,若是后面所有的值都比它之前的值小,直接写结果为0
从后往前遍历,同时记录后面的最大股价,和当前这个点买进时的最大收益,与之前的最大收益取个最大值
依次往前递推即可
下面是AC的算法
这道题的动态规划的思想在于,子问题分解为这个点买进时的收益与后面所有的买进时的收益的最大值之间选一个
依次往前即可,就成为一个线性求解的问题,
需要注意的是在这个题中也可以选择不买,若是后面所有的值都比它之前的值小,直接写结果为0
#include <iostream> #include <vector> #include <algorithm> using namespace std; int maxProfit(vector<int>& prices) { int len=prices.size(); if(prices.empty()||len==1) return 0; if(len==2) return max(prices[1]-prices[0],0); int maxprofit=prices[len-1]-prices[len-2]; int maxprices=prices[len-1]; for(int i=len-2;i>=0;i--) { maxprofit=max(maxprofit,maxprices-prices[i]); maxprices=max(maxprices,prices[i]); } return max(maxprofit,0); } int main() { }
相关文章推荐
- Leetcode 121. Best Time to Buy and Sell Stock 最佳股票售卖时(动态规划,数组,模拟)
- Leetcode 121. Best Time to Buy and Sell Stock 最佳股票售卖时(动态规划,数组,模拟)
- [LeetCode 121]Best Time to Buy and Sell Stock(动态规划)
- 【启发】leetcode - 121. Best Time to Buy and Sell Stock 【动态规划 + 连续区间问题 + 试探性购买】
- Leetcode(W8):121. Best Time to Buy and Sell Stock(动态规划)
- Leetcode 121 Best Time to Buy and Sell Stock 动态规划
- 动态规划入门级教学(leetcode)121.Best Time to Buy and Sell Stock
- 【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】
- leetcode121——Best Time to Buy and Sell Stock
- LeetCode(121) Best Time to Buy and Sell Stock
- Leetcode 121 Best Time to Buy and Sell Stock
- leetcode_[python/C++]_121/122/123/188.Best Time to Buy and Sell Stock I/II/III/IV
- LeetCode 188 Best Time to Buy and Sell Stock IV (动态规划 推荐)
- Java for LeetCode 121 Best Time to Buy and Sell Stock
- Leetcode-121. Best Time to Buy and Sell Stock
- LeetCode 121 Best Time to Buy and Sell Stock
- leetcode解题之121 # Best Time to Buy and Sell Stock
- LeetCode(121)Best Time to Buy and Sell Stock
- LeetCode 121 Best Time to Buy and Sell Stock
- LeetCode(121) Best Time to Buy and Sell Stock