Simple Java solution initially beats 10% but with optimization now beats 80%

  • 0

    My initial solution is the same as others and it turns out that it only beats 10%. Then I observed the test cases and found out that one small optimization you can do is to not even bother with calculating the max if your min is the same as prices[i], in which case max is just 0 (e.g. 100,99,98,97). After making the optimization, it now beats 80%.

    public int maxProfit(int[] prices) {
        if (prices == null) {
            return 0;
        int max = 0;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < prices.length; i++) {
            min = Math.min(min, prices[i]);
            if (min == prices[i]) {
            max = Math.max(max, prices[i] - min);
        return max;

Log in to reply

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