标签:best time to buy and leetcode 动态规划 算法 面试
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.
分析:从左向右遍历,记录左边的最小值,然后和当前值做差即可。class Solution { public: int maxProfit(vector<int> &prices) { int profit = 0,i,length =prices.size(); if(length <= 0)return profit; int buy = prices[0]; for(i = 0;i < length;i++) { if(prices[i] > buy) { profit = max(profit,prices[i] - buy); } else buy = prices[i]; } return profit; } };
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).
分析:题目说明可以多次买卖,但是同一时间只能有一股在手里。这样就可以在每次上升子序列之前买入,在上升子序列结束的时候卖出。相当于能够获得所有的上升子序列的收益。而且,对于一个上升子序列,比如:5,1,2,3,4,0
中的1,2,3,4序列来说,对于两种操作方案:
一,在1买入,4卖出;
二,在1买入,2卖出同时买入,3卖出同时买入,4卖出;
这两种操作下,收益是一样的。所以算法就是:从头到尾扫描prices,如果i比i-1大,那么price[i] – price[i-1]就可以计入最后的收益中。这样扫描一次O(n)就可以获得最大收益了。
class Solution { public: int maxProfit(vector<int> &prices) { int profit = 0,i,length =prices.size(); if(length <= 0)return profit; for(i = 0;i < length - 1;i++) { if(prices[i+1] > prices[i]) { profit += prices[i+1] - prices[i]; } } return profit; } };
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).
分析:动态规划,第一步从左向右扫描,先计算出子序列[0,...,i]中的最大利润,用一个数组保存下来,那么时间是O(n)。第二步是从右向左扫描,计算子序列[i,...,n-1]上的最大利润,时间也是O(n),然后对每一个i,进行遍历,求出最大利润,总的时间复杂度是O(n).
class Solution { public: int maxProfit(vector<int> &prices) { int profit = 0,i,length =prices.size(); if(length <= 0)return profit; vector<int> left_dp(length,0); left_dp[0] = 0; int buy = prices[0],price = 0; for(i = 1;i < length;i++)//从左向右 { if(prices[i] > buy) { price = max(price,prices[i]-buy); } else buy = prices[i]; left_dp[i] = price; } vector<int> right_dp(length,0); right_dp[length-1] = 0; price = 0; int send = prices[length-1]; for(i = length - 2;i >= 0;i--)//从右向左 { if(prices[i] < send) { price = max(price,send - prices[i]); } else send = prices[i]; right_dp[i] = price; } profit = 0; for(i = 0;i < length;i++)//遍历每一个i { if(left_dp[i] + right_dp[i] > profit)profit = left_dp[i] + right_dp[i]; } return profit; } };
leetcode 之 Best Time to Buy and Sell Stock
标签:best time to buy and leetcode 动态规划 算法 面试
原文地址:http://blog.csdn.net/fangjian1204/article/details/39134501