Always shows "ArrayIndexOutOfBoundsException" Exception


  • 0
    A

    Here is my solution.

    public class Solution {
        public int maxProfit(int[] prices) {
            int[] sell = new int[prices.length];
            for(int i = 0; i<prices.length; i++){
                for(int j = 0; j<i; j++){
                    sell[i] = Math.max(prices[i] - prices[j], sell[i]);
                }
            }
            int sellPrice = prices[0];
            int day = 0;
            for(int i = 0; i<prices.length; i++){
                if(sellPrice < prices[i]){
                    sellPrice = prices[i];
                    day = i;
                }
            }
            
            int buyPrice = prices[0];
            for(int i = 0; i<day; i++){
                buyPrice = Math.min(buyPrice, prices[i]);
            }
            
            return sellPrice - buyPrice;
        }
    }
    

    I'm not sure if it work, which is not a problem now. The problem is, it always shows Runtime Error at Line 9(int sellPrice = prices[0];) and Line 18(int buyPrice = prices[0];) as "java.lang.ArrayIndexOutOfBoundsException: 0". So what's wrong with it? How to fix it? Thank you so much.


  • 1
    S

    Your code must be able to handle edge cases correctly. For example, when the input array is an empty one, prices[0] does not even exist, hence the error.


Log in to reply
 

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