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).
public class Solution {
public int maxProfit(int[] prices) {
if (prices.length <= 1) {
return 0;
}
int i = 0;
int res = 0;
while (i < prices.length-1) {
while (i+1<prices.length && prices[i+1]<prices[i]) {
i++;
}
int buy = i;
i++;
while (i<prices.length && prices[i]>prices[i-1]) {
i++;
}
int sell = i-1;
res += prices[sell]-prices[buy];
}
return res;
}
}
本文介绍了一种算法,用于在股票市场中实现无限次买卖以获取最大利润,无需同时进行多笔交易。通过遍历股价数组,算法在价格下降前买入,在价格上升前卖出,实现利润最大化。
410

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



