2015年6月19日星期五

Best Time to Buy and Sell Stock II

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 len = prices.length;
        if (len <= 1) {
            return 0;
        }
        int i = 0;
        int res = 0;
        int profit = 0;
        while (i <= len - 1) {
            while (i < len - 1 && prices[i] > prices[i + 1]) {//寻找局部空间最小的点
                i++;// 因为最后一次不能为买入 所以i < len - 1
            }
            int buy = i;//最小点买入
            i++;
            while (i <= len - 1 && prices[i - 1] < prices[i]) {//局部最高点
                i++;
            }
            int sell = i - 1;//最高点卖出(因为最高点ipre 也满足while循环 i = ipre+1)
            profit += prices[sell] - prices[buy];
        }
        return profit;
    }
}

没有评论:

发表评论