LeetCode-02-The best time to buy and sell stocks II

The best time to buy and sell stocks II 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: Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on the 2nd day (stock price = 1), and on the 3rd day (stock price = 5) Sell, this exchange can make a profit = 5-1 = 4.
Then, buy on the 4th day (stock price = 3) and sell on the 5th day (stock price = 6). This exchange can make a profit = 6-3 = 3. Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on the 1st day (stock price = 1), and sell on the 5th day (stock price = 5) , This exchange can make a profit = 5-1 = 4.

Note that you cannot buy stocks one after another on the first day and the second day, and then sell them later.
Because this is involved in multiple transactions at the same time, you must sell the previous stocks before buying again. Example 3:
Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is completed, so the maximum profit is 0.

Analysis: Greedy thinking: buy from the first day, as long as there is a profit, you can sell it directly, and then buy again, and you can also sell once there is a profit, and the local optimal reaches the global optimal.

package day1;
public class day1 {
    
    
	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		int prices[]= {
    
    1,3,5,1,7,4};
		//int profit=maxProfit(prices);
		System.out.println(maxProfit(prices));
	}
	public static int maxProfit(int[] prices) {
    
    
		if(prices.length==0 || prices==null) {
    
    
			return 0;
		}
		int profit=0;
		for(int i=1;i<prices.length;i++) {
    
    
			if(prices[i]>prices[i-1]) {
    
    
				profit=prices[i]-prices[i-1];
			}
		}
		return profit;   
    }
}

Guess you like

Origin blog.csdn.net/TroyeSivanlp/article/details/108550352