The best time to buy and sell stocks: 121 questions

One. Problem Description

Given an array, which i-th element is a given stock i-day prices.

If you are only allowed up to complete a transaction (ie buying and selling a stock), to design an algorithm to compute the maximum profit you can get.

Note that you can not sell the stock before buying stocks.

Example 1:

Input: [7,1,5,3,6,4]

Output: 5

Explanation: Day 2 (stock price = 1) when buying on day 5 (stock price = 6), when sold, the largest profit = 6-1 = 5.

     Note that profits can not be 7-1 = 6, because the selling price must be greater than the purchase price.

Example 2:

Input: [7,6,4,3,1]

Output: 0

Explanation: In this case, no transaction is completed, the maximum profit is zero.

two. Problem-solving ideas

Body of ideas: the use of dynamic programming algorithm to solve it. Find the state transition function. N is the n-th row to the last row of the maximum value, i is a i-th row. The biggest difference n days ago Max (n) represents the profits, g (n) represents the n-th day of the stock price, n days ago f (n) represents the lowest stock price value.

Max(n)=Max(Max(n-1),g(n)-f(n-1))

Step one: according to the state transition equation, we can date from the first day, with the lowest stock price judgment, get the value of profits, if the value is greater than the profit temp, temp is equal to the maximum profit value, otherwise then later judgment until traverse end.

three. Results of the

When execution: 1 ms, beat the 99.97% of all users in java submission

Memory consumption: 37.1 MB, defeated 85.51% of all users in java submission

four. Java code

class Solution {
    public int maxProfit(int[] prices) {
         if(prices.length==0||prices==null){
             return 0;
         }
        int min=prices[0];
        int max=prices[0];
        int temp=0;
        for(int i=0;i<prices.length;i++) {
            if(prices[i]<min) {
                min=prices[i];
                max=prices[i];
            }else if(prices[i]>max) {
                max=prices[i];
                temp=Math.max(temp, max-min);
            }
        }
        return temp;
    }
}

 

Guess you like

Origin www.cnblogs.com/xiaobaidashu/p/11887791.html