题目
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 ret=0;
if(prices.length<2){
return ret;
}
for(int i=1;i<prices.length;i++){
if(prices[i]>prices[i-1]){
ret+=(prices[i]-prices[i-1]);
}
}
return ret;
}
}
相关题目的参考链接
http://liangjiabin.com/blog/2015/04/leetcode-best-time-to-buy-and-sell-stock.html
股票买卖最大利润算法
本文介绍了一种算法,用于计算给定股票价格数组时的最大可能利润。该算法允许进行多次买入卖出操作,但每次卖出后才能再次买入。通过遍历价格数组并累加每次上涨的价格差来获得最大利润。
465

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



