121. Best Time to Buy and Sell Stock——Leetcode

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

题目大意:给定一组股票的价格,买卖一次,求最大的收益。

思路:扫一遍,记录最小值,当前价格减去最小值就是当前可获得的最大收益,从这些可能的收益值中取最大的。

public int solution(int[] arr) {
    if(arr == null || arr.length == 0) {
        return 0;
    }
    int[] dp = new int[arr.length];
    int min = arr[0];
    for(int i = 1;i<arr.length;i++) {
        dp[i] = Math.max(dp[i-1], arr[i] - min);
        if (arr[i] < min) {
            min = arr[i];
        }
    }
    return dp[arr.length - 1];
}

原文地址:https://www.cnblogs.com/aboutblank/p/9645383.html