LeetCode - BestTimetoBuyandSellStockII

来源:互联网 发布:流动商贩全国数据 编辑:程序博客网 时间:2024/06/05 10:26

/**

 * 问:已知某股票的价格数组,且该股票可买卖很多次,但是只有卖了才能重新买。求最大收益。

 * 解:贪心算法:只要能赚钱就卖。

 */

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));

}

}
0 0
原创粉丝点击