Question
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).
Code
public int maxProfit(int[] prices) {
int maxProfit = 0;
int len = prices.length;
for (int i = 1; i < len; i++) {
int dif = prices[i] - prices[i - 1];
if (dif > 0) {
maxProfit += dif;
}
}
return maxProfit;
}
本文介绍了一个在股票市场中通过多次买卖来最大化利润的算法。该算法允许无限次交易,但要求每次交易后必须卖出股票才能进行下一次购买。通过遍历价格数组并计算相邻元素之间的差值,此算法能够确定最佳交易时机,从而实现利润的最大化。
484

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



