标签:
Title:
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.
思路:对于ith个,找出之前的最小值,然后用当前的减去最小值,看是否是最大的利润。实际上就是动态规划
dp[i] = max{dp[i-1], prices[i] - minprices} ,minprices是区间[0,1,2...,i-1]内的最低价格
class Solution { public: int maxProfit(vector<int>& prices) { if (prices.size() < 2) return 0; int min_price = prices[0]; int profit = 0; for (int i = 1; i < prices.size(); i++){ min_price = min(min_price,prices[i-1]); profit = max(profit,prices[i]-min_price); } return profit; } };
按照股票差价构成新数组 prices[1]-prices[0], prices[2]-prices[1], prices[3]-prices[2], ..., prices[n-1]-prices[n-2]。求新数组的最大子段和就是我们求得最大利润,假设最大子段和是从新数组第 i 到第 j 项,那么子段和= prices[j]-prices[j-1]+prices[j-1]-prices[j-2]+...+prices[i]-prices[i-1] = prices[j]-prices[i-1], 即prices[j]是最大价格,prices[i-1]是最小价格,且他们满足前后顺序关系。
class Solution { public: int maxProfit(vector<int> &prices) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int len = prices.size(); if(len <= 1)return 0; int res = 0, currsum = 0; for(int i = 1; i < len; i++) { if(currsum <= 0) currsum = prices[i] - prices[i-1]; else currsum += prices[i] - prices[i-1]; if(currsum > res) res = currsum; } return res; } };
LeetCode: Best Time to Buy and Sell Stock
标签:
原文地址:http://www.cnblogs.com/yxzfscg/p/4511435.html