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) {
int result = 0;
int diff = 0;
for(int i = 0; i < prices.length - 1; i++){
diff = prices[i + 1] - prices[i];
if(diff > 0)
result += diff;
}
return result;
}
}
本文介绍了一种计算股票交易最大利润的算法。该算法允许进行多次买卖操作,但每次卖出后才能再次购买。通过比较连续两天的价格差异,如果后一天价格高于前一天,则将差额计入总利润。

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



