来源:Leetcode
原帖:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
题目:
Say you have an array for which the i-th 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 (i.e., buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
代码:
1]考虑每一次交易
2]考虑每一次增长
原帖:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
题目:
Say you have an array for which the i-th 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 (i.e., buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
代码:
1]考虑每一次交易
class Solution {
public:
//计算从波谷到波峰的增长
int maxProfit(vector<int>& prices) {
if (prices.empty()) return 0;
int N = prices.size();
int res = 0, buy = 0;
for (int i = 1; i < N-1; ++i) {
if (prices[i] > prices[i-1] && prices[i] >= prices[i+1]) { // 特别注意>,>=
res += prices[i] - prices[buy];
} else if (prices[i] <= prices[i-1] && prices[i] < prices[i+1]) { // <=, <
buy = i;
}
}
if (prices[N-1] > prices[N-2]) {
res += prices.back() - prices[buy];
}
return res;
}
};
2]考虑每一次增长
class Solution {
public:
//计算每段相邻的增长
int maxProfit(vector<int> &prices) {
int res = 0;
for (int i = 1; i < prices.size(); ++i) {
if (prices[i] > prices[i - 1]) {
res += prices[i] - prices[i - 1];
}
}
return res;
}
};
No comments:
Post a Comment