Java LeetCode 714. The best time to buy and sell stocks includes handling fees

Given an integer array prices, the i-th element represents the stock price on the i-th day; a non-negative integer fee represents the transaction fee for stocks.
You can complete transactions unlimited times, but you will need to pay a handling fee for each transaction. If you have already bought a stock, you can no longer buy stocks until you sell it.
Returns the maximum profit obtained.
Note: A transaction here refers to the entire process of buying, holding and selling stocks. You only need to pay a handling fee for each transaction.
Example 1:
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit that can be achieved:
buy here prices[0] = 1
sell here Out prices[3] = 8
Buy here prices[4] = 4
Sell ​​here prices[5] = 9
Total profit: ((8-1)-2) + ((9-4)-2 ) = 8.

class Solution {
public int maxProfit(int[] prices, int fee) {
int pr_0=0;
int pr_1=Integer.MIN_VALUE;

    for(int i=0;i<prices.length;i++){
        pr_0 = Math.max(pr_0,pr_1+prices[i]);
        pr_1 = Math.max(pr_1,pr_0-prices[i]-fee);
    }

    return pr_0;
}

}

Guess you like

Origin blog.csdn.net/sakura_wmh/article/details/111601663