第一题的思路就是更新两个值,先是res=max(res,price[i]-mincount)后是已知的最小值 mincount=min(mincount,price[i])然后遍历就完事了。
class Solution {
public:
int maxProfit(vector<int>& price) {
int n = price.size();
if (n <= 0)
return 0;
int res = 0;
int mincount = price[0];
for (int i = 1; i < n; i++)
{
res = max(res, price[i] - mincount);
mincount = min(mincount, price[i]);
}
return res;
}
};
第二题就是只要price[i+1]>price[i],res+=price[i+1]-price[i],这个最开始有点迷就是当天既可以买又可以卖?后来想明白了,就相当于当天跳过了嘛。
class Solution {
public:
int maxProfit(vector<int>& price) {
int n = price.size();
if (n <= 0)
return 0;
int res = 0;
for (int i = 0; i < n-1; i++)
{
if (price[i + 1]>price[i])
res += price[i + 1] - price[i];
}
return res;
}
};
第三题n2的复杂度就是枚举每一天当成分界点一般情况是会超时的,那跟第一题有啥区别呢,就是相当于正向的第一题加反向再来一遍,然后求和,表示为每天作为分界线的res[i],也看到了一个比较有意思的解法。
class Solution {
public:
int maxProfit(vector<int>& price) {
int n = price.size();
if (n <=0)
return 0;
int res = 0;
vector<int> tmp(n, 0);
int mincount = price[0];
int maxcount = price[n - 1];
int temp1 = 0, temp2 = 0;
for (int i = 1; i < n; i++)
{
temp1 = max(temp1, price[i] - mincount);
mincount = min(mincount, price[i]);
tmp[i] = temp1;
}
for (int i = n - 2; i >= 0; i--)
{
maxcount = max(maxcount, price[i]);
temp2 = max(temp2, maxcount - price[i]);
res = max(res, temp2 + tmp[i]);
}
return res;
}
};
class Solution {
public:
int maxProfit(vector<int>& price) {
int n = price.size();
if (n <= 0)return 0;
int sell1 = 0, sell2 = 0, buy1 = INT_MIN, buy2 = INT_MIN;
for (int i = 0; i < n; i++)
{
buy1 = max(buy1, -price[i]);
sell1 = max(sell1, price[i] + buy1);
buy2 = max(buy2, sell1 - price[i]);
sell2 = max(sell2, price[i] + buy2);
}
return sell2;
}
};
第四题就是k了,在leetcode上看到了一个通用解法,三维数组状态转移,有点像随机过程里面的马尔科夫链,反正动态规划的核心就是那个转移方程,但是有点繁琐。