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==null || prices.length<=1) return 0;
int profit=0;
int buy=prices[0];
for(int i=1;i<prices.length;i++){
if(prices[i]<prices[i-1]){
profit+=prices[i-1]-buy;
buy=prices[i];
}
}
if(prices[prices.length-1]>buy)
profit+=(prices[prices.length-1]-buy);
return profit;
}
}
本文介绍了一种用于计算股票交易中最大可能利润的算法。该算法允许进行多次买入和卖出操作,但每次卖出后才能再次购买。通过遍历价格数组并跟踪价格波动,可以有效地找出最佳买卖时机。
412

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



