【LeetCode】122. Best Time to Buy and Sell Stock II(Java)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Rabbit_Judy/article/details/88051766

题目描述:假设有一个数组,其中第i个元素是给定股票在第i天的价格。设计一种寻找最大利润的算法。您可以完成任意多的交易(买一股,卖一股,多次)。

注:阁下不得同时进行多项交易(即你必须先把股票卖了,然后再买。

Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

public class Solution {
    /**
     * 只要第二天的股价比当天的高,那就在当天买进,第二天卖出,这样利润最大
     *
     * @param prices
     * @return
     */
    public static int maxProfit(int[] prices) {
        int profit = 0;
        for (int i = 0; i < prices.length - 1; i++) {
            if (prices[i] < prices[i + 1])
                profit = profit + prices[i + 1] - prices[i];
        }
        return profit;
    }

    public static void main(String[] args) {
        long start = System.nanoTime();
        int[] price = new int[]{7, 1, 5, 3, 6, 4};
        System.out.println(maxProfit(price));
        long end = System.nanoTime();
        System.out.println("运行时间:" + (end - start) + "ns");
    }
}

猜你喜欢

转载自blog.csdn.net/Rabbit_Judy/article/details/88051766