您的位置:首页 > 其它

leetcode-121-Best Time to Buy and Sell Stock

2017-02-14 13:57 344 查看

问题

题目:[leetcode-121]

思路

蛮力法,计算所有可能的情形。O(N2)的复杂度。

代码(TLE)

class Solutiocn {
public:
int maxProfit(vector<int>& prices) {
int sz = prices.size();
if(!sz) return 0;

int ans = 0;
for(int i = 0; i < sz; ++i){
for(int j = i + 1; j < sz; ++j){
int profix = prices[j] - prices[i];
ans = std::max(ans, profix);
}
}
return ans;
}
};


思路1

看了最长连续字段和的代码。有点启发。首先这两个问题本质都是找一个区间,虽然后面这个其实不是找区间。但是需要找到start,end两个下标。

既然,前面的题目都可以解。这个题我觉得应该也可以。

对比之前的思路,一定要考虑当前数值和之前数值的关系,我就是按着这个方向才想到了解决办法。O(N)的复杂度。DP求解。

当然,我下面你的做法还是标记了买入点和卖出点。最大字段和是没有明确的标记,它是当dp[i-1]<=0时,重新计算。就相当于标记了开始点。

定义:dp[i]表示在第i点卖出时的利润,则状态转移函数如下:

dp[i]={prices[i]−prices[buy]−1 and buy=i, prices[buy]<prices[i], prices[buy]≥prices[i] (1)

代码1

class Solution {
public:
int maxProfit(vector<int>& prices) {
int sz = prices.size();
if(!sz) return 0;

int buy = 0;
int max = 0;
std::vector<int> dp(sz, int());
dp[0] = -1;
for(int i = 1; i < sz; ++i){
if(prices[buy] < prices[i])
dp[i] = prices[i] - prices[buy];
else{
buy = i;
dp[i] = -1;
}
max = std::max(max, dp[i]);
}
return max;
}
};


代码2

省去空间的开销。

class Solution {
public:
int maxProfit(vector<int>& prices) {
int sz = prices.size();
if(!sz) return 0;

int buy = 0;
int max = 0;
int profit = -1;

for(int i = 1; i < sz; ++i){

if(prices[buy] < prices[i])
profit = prices[i] - prices[buy];
else{
buy = i;
profit = -1;
}
max = std::max(max, profit);
}
return max;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: