LeetCode每日一题:买卖股票的最好时机 2

问题描述

Say you have an array for which the i 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).

问题分析

这题相比上一题,可以多次买入卖出,所以我们可以用贪心算法解决:
用dayProfit[i]记录当天股票相比于前一天的涨跌,若dayProfit[i]>0,则进行买卖

代码实现

public int maxProfit(int[] prices) {
        if (prices.length == 0) return 0;
        int[] dayProfit = new int[prices.length];
        Arrays.fill(dayProfit, 0);
        for (int i = 1; i < prices.length; i++) {
            dayProfit[i] = prices[i] - prices[i - 1];
        }
        int profit = 0;
        for (int i = 1; i < prices.length; i++) {
            if (dayProfit[i] > 0) {
                profit = profit + dayProfit[i];
            }
        }
        return profit;
    }

你可能感兴趣的:(LeetCode每日一题:买卖股票的最好时机 2)