Leetcode problem solution-the best time to buy and sell stocks

The best time to buy and sell stocks I

Problem Description

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

You can only choose to buy this stock on a certain day, and choose to sell the stock on a different day in the future. 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:

输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5
     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。

Example 2:

输入:prices = [7,6,4,3,1]
输出:0
解释:在这种情况下, 没有交易完成, 所以最大利润为 0

Problem-solving ideas:

Brute force method:

We need to find the maximum difference (ie, maximum profit) between two numbers in a given array. In addition, the second number (sell price) must be greater than the first number (buy price).

Formally, for each group of ii and jj (where j> ij>i) we need to find \max(prices[j]-prices[i])max(prices[j]−prices[i]).

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        int tempProfit []=new int[prices.length];
        if(prices.length==0){
    
    
            return 0;
        }
		tempProfit[0]=0;
		int maxPro=0;
		for(int i=1;i<prices.length;i++){
    
    
			int temp;
			for(int j=i-1;j>=0;j--){
    
    
				if(prices[i]>prices[j]){
    
    
					temp=prices[i]-prices[j]+tempProfit[j];
					if(temp>tempProfit[i]){
    
    
						tempProfit[i]=temp;
					}
				}
			}
			if(tempProfit[i]>maxPro){
    
    
				maxPro=tempProfit[i];
			}
		}
		
		return maxPro;
    }
}

how are you:

Suppose the given array is: [7, 1, 5, 3, 6, 4]
If we draw the numbers in the given array on the chart, we will get:
Insert picture description here
Let's assume that we buy stocks by ourselves. Over time, every day we can choose whether to sell the stock or not. So, suppose that on the i day, if we want to sell stocks today, how much money can we make?

Obviously, if we were really buying and selling stocks, we would definitely think: It would be great if I bought the stocks at the lowest point in history! Great. In the title, we only need to record a historical minimum price minprice with a variable, and we can assume that our stock was bought that day. Then the profit we can get from selling stocks on the i day is prices[i]-minprice.

Therefore, we only need to traverse the price array once, record the lowest point in history, and then consider this question every day: If I bought at the lowest point before this, how much money can I make by selling today? When all the days are considered, we get the best answer.

If you plan to sell stocks on the i-th day, then the maximum profit difference must be the lowest point between [0, i-1] to buy; so traverse the array and find the maximum difference for each selling opportunity in turn , And then take the maximum value from it .

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        int minPrice=prices[0];
        int n=prices.length;
        int res=0;
        for(int i=0;i<n;i++){
    
    
            //记录这之前的最低价格
            if(minPrice>prices[i]){
    
    
                minPrice=prices[i];
            }else{
    
    
            //如果大于最低价格,就尝试着卖出,并假设最低点买入
                res=Math.max(res,prices[i]-minPrice);
            }
        }
        return res;
    }
}

The best time to buy and sell stocks II

Problem Description

Given an array, its i-th element is the price of a given stock on the i-th day.

Design an algorithm to calculate the maximum profit you can get. You can complete as many transactions as possible (buying and selling a stock multiple times).

Note: You cannot participate in multiple transactions at the same time (you must sell the previous stocks before buying again).

Example 1:

输入: [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4
     随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3

Example 2:

输入: [1,2,3,4,5]
输出: 4
解释: 在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4
     注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。
     因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。

Example 3:

输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0

Problem-solving ideas: Greedy

Insert picture description here
It should be noted that the greedy algorithm can only be used to calculate the maximum profit, and the calculation process is not the actual trading process .
Since there are no restrictions on the purchase of stocks, the whole problem is equivalent to finding x disjoint intervals (li,ri),
Insert picture description here
where li means buying on day li, ri means buying on day ri,
and we notice that (li ,ri] The contribution value a[ri]-a[li] in this interval is actually equivalent to (li,li+1),(li+1,li+2),...,(ri-1,ri )
Insert picture description here
Therefore, the problem can be simplified to find x intervals (li, li+1) of length 1 to maximize the total value. From the
greedy perspective, we can maximize the answer every time we choose an interval whose contribution is greater than 0, so the final answer is
Insert picture description here
Where n is the length of the array.
Consider the example in the title [1,2,3,4,5], the length of the array is n=5, because there is a[i]>a[i for all 1< i <n −1], so the answer is,
Insert picture description here
but the actual transaction process is not to buy 4 times and sell 4 times, but to buy on the 11th day and sell on the 55th day.

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        int profit=0;
        int n=prices.length;
        for(int i=1;i<n;i++){
    
    
            if(prices[i]>prices[i-1]){
    
    
                profit+=prices[i]-prices[i-1];
            }
        }
        return profit;
    }
}

Guess you like

Origin blog.csdn.net/qq_39736597/article/details/114282280