4
头图

The best time to buy and sell stocks II

Title description: Given an array prices, where prices[i] is the price of a given stock on the i day.

Design an algorithm to calculate the maximum profit you can get. You can complete as many transactions as possible (buying and selling a stock multiple times).

Note: You cannot participate in multiple transactions at the same time (you must sell the previous stocks before buying again).

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Greedy Algorithm

Because there is no limit to the number of transactions, in order to get the maximum profit of multiple transactions, in fact, it is necessary to get the positive cumulative sum of the positive difference, because for any period of positive positive difference, it can actually be assumed to be done once The buying and selling operation, if it is a continuous positive difference, can actually be regarded as a buying and selling. The smallest number is a buy operation, and the largest number is a sell operation. Therefore, according to the greedy algorithm, the specific processing process is as follows:

  • Traverse the array, and then add the positive difference of each segment to the income, and finally return the result, which is the expected maximum income.

You can refer to LeetCode-121-the best time to buy and sell stocks , there should be a dynamic programming solution.

/**
 * 买卖股票的最佳时机 II
 */
public class LeetCode_122 {

    /**
     * 贪心算法
     *
     * @param prices
     * @return
     */
    public static int maxProfit(int[] prices) {
        // 预期最大的收益值
        int result = 0;
        for (int i = 1; i < prices.length; i++) {
            // 获取每段的正向差值,即为实际的买卖操作
            result += Math.max(0, prices[i] - prices[i - 1]);
        }
        return result;
    }

    public static void main(String[] args) {
        int[] prices = new int[]{7, 1, 5, 3, 6, 4};
        // 测试用例,期望输出: 7
        System.out.println(maxProfit(prices));
    }
}
【Daily Message】 Life is half fireworks and half poetry. Holding fireworks in hand to seek life, with poetry in mind to seek love.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!