Leetcode Best Time to Buy and Sell Stock II OJ 刷题 算法

来源:互联网 发布:linux shell执行exe 编辑:程序博客网 时间:2024/06/10 01:54

Best Time to Buy and Sell Stock II

ay 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).

思考

按理好像是要动态规划做

投机取巧, 直接把 上升段的值相加

直接比较相邻 2 个数的值, 就可以了

因为如果有连续跨越几个数的上升段, 也包含了相邻 2 个数的上升段


Solution

public class BestTimeBuySellStock {    public static void main(String[] args) {        System.out.println(maxProfit(new int[] { 1, 3, 4, 0, 1, 3, 2 }));        System.out.println(maxProfit(new int[] { 3, 3,1,5,10,3, 4, 0, 1, 3, 2 }));    }    public static int maxProfit(int[] prices) {        int result = 0;        for (int i = 1; i < prices.length; i++) {            if (prices[i] > prices[i - 1]) {                result += prices[i] - prices[i - 1];            }        }        return result;    }}

其他解法

public static int maxProfit(int[] prices) {        int result = 0;        if (prices.length == 0) {            return 0;        }        int startPrice = prices[0];        int endPrice = prices[0];        for (int i = 1; i < prices.length; i++) {            while (i < prices.length && startPrice < prices[i]) {                if (prices[i] < endPrice) {                    break;                } else {                    endPrice = prices[i];                }                i++;            }            result += endPrice - startPrice;            if (i < prices.length) {                startPrice = prices[i];                endPrice = prices[i];            }        }        return result;    }

这个方法找出 连续上升段的起始值和终点值

将所有上升段的差值 累记 就得到了最大利润

0 0
原创粉丝点击