Java Min/Max

  • 0

    My idea is to maintain (minPrice, curProfit, gProfit). minPrice will be the minimum price in the timeframe we are currently in with curProfit being the max current profit to make from the minPrice. If we encounter a price that is less than or equal to minPrice + curProfit, we add the curProfit to our gProfit and begin looking for a new max curProfit with a minProfit of that new price. With this technique, we constantly look for curProfits when price differences are within the range of the fee. If the curProfit gets too large or if the minPrice gets too small, we will make the profit.

    public class Solution {
        public int maxProfit(int[] prices, int fee) {
            int minPrice = Integer.MAX_VALUE, curProfit = 0, gProfit = 0;
            for (int i = 0; i < prices.length; i++) {
                minPrice = Math.min(minPrice, prices[i]);
                if (minPrice + curProfit >= prices[i]) {
                    gProfit += curProfit;
                    curProfit = 0;
                    minPrice = prices[i];
                } else {
                    curProfit = Math.max(curProfit, prices[i] - minPrice - fee);
            return gProfit + curProfit;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.