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).
Accept: 6ms
思路:
- 同 Stock I,先求diff,然后将 diff[i] > 0的全部加起来即可。
int diff[100000];
int maxProfit(int prices[], int n){
for (int i = 0; i < n - 1; ++i) {
diff[i] = prices[i+1] - prices[i];
}
int total = 0;
for (int i = 0; i < n - 1; ++i) {
if (diff[i] > 0) {
total += diff[i];
}
} // for
return total;
}
本文介绍了一种股票交易策略算法,该算法允许进行多次买卖操作以最大化收益,并且确保每次卖出后才能再次购买。通过计算每日价格变化并累加所有正向收益来实现利润最大化。
310

被折叠的 条评论
为什么被折叠?



