/**
* 问:已知某股票的价格数组,且该股票可买卖很多次,但是只有卖了才能重新买。求最大收益。
* 解:贪心算法:只要能赚钱就卖。
*/public class BestTimetoBuyandSellStockII {
public int maxProfit(int[] prices) {
int result = 0;
for (int i=0; i<prices.length-2; i++) {
if (prices[i+1] >prices[i])
result += prices[i+1] - prices[i];
}
return result;
}public static void main(String[] args) {
int[] prices = {9, 1, 2, 8, 3, 7};
System.out.println("最大收益:" + new BestTimetoBuyandSellStockII().maxProfit(prices));
}}
本文介绍了一个简单的股票交易策略算法,该算法使用贪心策略来最大化股票买卖的收益。通过遍历股票价格数组,每当遇到价格上涨的情况,即刻卖出,累积所有能够获利的差价作为最终的最大收益。
416

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



