做了一下 Google 的 Best Time to Buy and Sell Stock II# JobHunting - 待字闺中
w*x
1 楼
/*
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).
*/
class Solution {
public:
int maxProfit(vector &a) {
int n = a.size();
int* rec = new int[n];
rec[0] = 0;
int nRet = 0;
for (int i = 1; i < n; i++)
{
int nMax = rec[i-1];
for (int j = i-1; j >= 0; j--)
{
int nBase = j-1 < 0 ? 0 : rec[j-1];
if (nBase + a[i] - a[j] > nMax)
nMax = nBase + a[i] - a[j];
}
rec[i] = nMax;
nRet = max(nRet, nMax);
}
delete[] rec;
return nRet;
}
};
//greedy O(n) approach
class Solution {
public:
int maxProfit(vector &a) {
int nPrev = 0;
for (int i = 1; i < a.size(); i++)
nPrev = (a[i] < a[i-1]) ? nPrev : nPrev + a[i] - a[i-1];
return nPrev;
}
};
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).
*/
class Solution {
public:
int maxProfit(vector
int n = a.size();
int* rec = new int[n];
rec[0] = 0;
int nRet = 0;
for (int i = 1; i < n; i++)
{
int nMax = rec[i-1];
for (int j = i-1; j >= 0; j--)
{
int nBase = j-1 < 0 ? 0 : rec[j-1];
if (nBase + a[i] - a[j] > nMax)
nMax = nBase + a[i] - a[j];
}
rec[i] = nMax;
nRet = max(nRet, nMax);
}
delete[] rec;
return nRet;
}
};
//greedy O(n) approach
class Solution {
public:
int maxProfit(vector
int nPrev = 0;
for (int i = 1; i < a.size(); i++)
nPrev = (a[i] < a[i-1]) ? nPrev : nPrev + a[i] - a[i-1];
return nPrev;
}
};