买卖股票的题,求最大利润。看上去十分高大上,答案让人吐血。原理很简单:买股票的人都喜欢抄底买涨到最高时候卖啊。
这道题不能想太多啊,不用关心什么时候买什么时候卖的问题:只要在涨,把利润加进去就好了。。。
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).
Solution:
public class Solution {
public int maxProfit(int[] prices) {
int max=0;
for(int i=0; i<prices.length-1;i++){
if(prices[i]<=prices[i+1]){
max+=prices[i+1]-prices[i];
}
}
return max;
}
}
本文介绍了一种简单有效的算法来解决股票交易中的最大利润问题。该算法允许进行多次买卖操作,但不能同时持有多个仓位。通过遍历价格数组并累加每次上涨带来的利润,可以快速得出最大收益。
499

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



