Code works but could not be submitted


  • 0
    Z

    Why this following code works but could not be submitted?
    The following error:
    Runtime Error Message:
    Line 4: java.lang.ArrayIndexOutOfBoundsException: 0
    Last executed input:
    []

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

  • 0

    @zhyzhu-gmail-com I know little about java but your code can be simply fixed by

    if (prices.length == 0) return 0;
    

  • 0
    Z

    Thanks a lot!


Log in to reply
 

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