1. 程式人生 > >LeetCode#122: Best Time to Buy and Sell Stock II

LeetCode#122: Best Time to Buy and Sell Stock II

此題應該分清楚這兩種情況:在一段時間內如果價格一路上升,則最早買、最晚賣時利潤是最高的;如果中途有價格下跌而產生了低谷與高峰的情況,則在低谷買、高峰賣時利潤最高。

class Solution {
    public int maxProfit(int[] prices) {
        int maxProfit = 0;
        int lo = 0;
        int hi = 0;
        for(int i = 0; i < prices.length; i++) {
        	while(i < prices.length-1  &&
prices[i] > prices[i+1]) i++; lo = i; while(i < prices.length-1 && prices[i] < prices[i+1]) i++; hi = i; maxProfit += prices[hi] - prices[lo]; } return maxProfit; } }