标签:algorithm dynamic program leetcode best time to buy and
1. 题目: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.
解法:int maxProfit(vector<int>& prices) { if(prices.size()<=1) return 0; int minPrice=prices[0]; int maxPro=0; for(int i=1; i<prices.size(); i++){ minPrice=min(prices[i], minPrice); maxPro=max(maxPro, prices[i]-minPrice); } return maxPro; }
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).
int maxProfit(vector<int>& prices) { int retProfit=0; for(int i=1; i<prices.size(); i++){ if(prices[i]>prices[i-1]) retProfit+=prices[i]-prices[i-1]; } return retProfit; }
3. 题目:Best
Time to Buy and Sell Stock III
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).
解法:
主要思想:查看当前位置左边+右边分别进行交易一次,的最大利润之和
int maxProfit(vector<int>& prices) { if(prices.size()<=1) return 0; vector<int> begin_end(prices.size(), 0); vector<int> end_begin(prices.size(), 0); int minP=prices[0]; begin_end[0]=0; for(int i=1; i<prices.size(); i++){ minP=min(minP, prices[i]); begin_end[i]=max(prices[i]-minP, begin_end[i-1]); } int maxP=prices[prices.size()-1]; end_begin[prices.size()-1]=0; for(int i=prices.size()-2; i>=0; i--){ maxP=max(maxP, prices[i]); end_begin[i]=max(maxP-prices[i], end_begin[i+1]); } int maxPro=begin_end[0]+end_begin[0]; for(int i=1; i<prices.size(); i++){ if(begin_end[i]+end_begin[i]>maxPro) maxPro=begin_end[i]+end_begin[i]; } return maxPro; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
Best Time to Buy and Sell Stock
标签:algorithm dynamic program leetcode best time to buy and
原文地址:http://blog.csdn.net/jisuanji_wjfioj/article/details/46688179