Given an array prices , its i element prices[i] represents the price of a given stock on the i

You can only choose one day buy this stock, and choose a different day in the sell the stock 16193a451988cf. Design an algorithm to calculate the maximum profit you can get.

Return the maximum profit you can get from this transaction. If you cannot make any profit, return 0 .

Example 1:

input: [7,1,5,3,6,4]
output: 5
explained: on the 2nd day (stock price = 1) and sold on the 5th day (stock price = 6), the maximum profit = 6-1 = 5.
Note that the profit cannot be 7-1 = 6, because the selling price needs to be greater than the buying price; at the same time, you cannot sell the stock before buying.

Example 2:

input: prices = [7,6,4,3,1]
output: 0
: In this case, no transaction is completed, so the maximum profit is 0.

Violence law

Write two layers of for loops, and compare them one by one. They can definitely be compared, and the code will not be written.

Time complexity: O(n2)
Space complexity: O(1)

Dynamic programming

Definition sub-problem

Suppose we already know i-1 maximum profit companies and is dp[i-1] , apparently i maximum profit consecutive stock is either dp[i-1] , or is prices[i] - minprice ( minprice front i-1 minimum value of stocks).

State transition equation

dp[i] = Math.max(dp[i-1], prices[i] - minprice)

Boundary conditions

dp[0] = 0

code implementation

Because when we calculate dp[i] , we only care about dp[i-1] and prices[i] , so we don't need to dp array, just set a max save dp[i-1] .

public class Solution {
    public int maxProfit(int[] prices) {
        int max = 0;
        int minprice = prices[0];
        for (int i=1; i<prices.length; i++) {
            minprice = Math.min(prices[i], minprice);
            max = Math.max(max, prices[i] - minprice);
        }
        return max;
    }
}

Time complexity: O(n)
Space complexity: O(1)


一杯绿茶
199 声望17 粉丝

人在一起就是过节,心在一起就是团圆


引用和评论

0 条评论