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.
设f(i)表示以第prices[i]卖出时所获的最大利润,则f(i) = max{prices[i] - prices[k], 0<= k <= i}
= prices[i] - min{prices[k], 0 <= k <= i}
那么最终所能获利的最大值为:
ans = max{f(i), 0 <= i < n}
恰好f(i)中的前i个的最小值可以在计算过程中顺便计算出来,因此代码如下:
class Solution {
public:
int maxProfit(vector<int> &prices) {
int mp = 0, minv = INT_MAX;
for (int i = 0; i < prices.size(); i++)
{
minv = min(minv, prices[i]);
mp = max(mp, prices[i] - minv);
}
return mp;
}
};
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> &prices)
{
int ans = 0;
for (int i = 1; i < prices.size(); i++)
if (prices[i] - prices[i - 1] > 0)
ans += prices[i] - prices[i - 1];
return ans;
}
};
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).
设f(k)表示前k天所获最大利润,g(k)表示后n-k天所获最大利润,那么枚举一下k,所得的f(k)+g(k)的最大值即为答案。(k可为0,这允许了只进行一次交易的可能)
f(k) = max{ prices[i] - min{prices[j]}, 0 <= j <= i <= k }
g(k) = max{max{prices[j]} - prices[i], k <= i <= j <= n }
ans = max{f(k) + g(k)}
class Solution {
public:
int maxProfit(vector<int> &prices)
{
int n = (int)prices.size();
vector<int> f(n), g(n);
int minv = INT_MAX, maxv = INT_MIN, ans = 0;
for (int i = 0; i < n; i++)
{
minv = min(minv, prices[i]);
f[i] = ans = max(ans, prices[i] - minv);
}
ans = 0;
for (int i = n - 1; i >= 0; i--)
{
maxv = max(maxv, prices[i]);
g[i] = ans = max(ans, maxv - prices[i]);
}
ans = 0;
for (int k = 0; k < n; k++)
ans = max(ans, f[k] + g[k]);
return ans;
}
};