题目:
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).
解决方法一: Time Limit Exceed,考虑优化
public class Solution {
public int maxProfit(int[] prices) {
if(null==prices||prices.length<=0) return 0;
int l[] = new int[prices.length];
for(int i=0;i<prices.length;i++){
for(int j=i;j>=0;j--){
if(j-1>=0)
l[i]= (prices[i]-prices[j]+l[j-1])>l[i] ? (prices[i]-prices[j]+l[j-1]):l[i];
else
l[i]=(prices[i]-prices[j])>l[i] ? (prices[i]-prices[j]):l[i];
}
}
return l[prices.length-1];
}
}
解决方法二:Runtime: 3 ms
public class Solution {
public int maxProfit(int[] prices) {
if(null==prices||prices.length<=0) return 0;
int profit=0;
for(int i=0;i<prices.length-1;i++){
if(prices[i+1]>prices[i])
profit+=prices[i+1]-prices[i];
}
return profit;
}
}
参考:
本文介绍了一种求解股票买卖最大利润的算法。该算法允许多次买卖操作但不能同时持有股票,通过一次遍历即可得到最大利润,实现高效求解。
591

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



