首页 > 代码库 > Leetcode Best Time to Buy and Sell Stock
Leetcode 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.
一开始看到题目以为是最大值减去最小值即可,但由于买发生在卖前面,所以,最小值买进最大值卖出只有在最小值在最大值前面时才发生
本题思路是:遍历时记录前面最小值点,然后max(当前元素-前面最小值)即可
class Solution {public: int maxProfit(vector<int> &prices) { if(prices.size() == 0) return 0; int res = 0, minv = prices[0]; for(int i = 1; i < prices.size(); ++ i){ res = max(res,prices[i]-minv); minv = min(prices[i],minv); } return res; }};
本题也可以考虑利用动态规划去做
设决策变量为dp[i],表示i个元素卖出的最大利润
则状态转移方程为
dp[i+1] = prices[i+1]-prices[i]+max(0,dp[i])
由于前面的dp[i],在dp[i+1]后不会被使用,故只需要一个状态变量,不断更新这个状态变量即可
class Solution {public: int maxProfit(vector<int> &prices) { int dp = 0, res = 0; for(int i = 1; i < prices.size(); ++ i){ dp = prices[i]-prices[i-1] + max(0,dp); res = max(res,dp); } return res; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。