def change(amount: Int, coins: Array[Int]): Int = {
val dp = Array[Int](amount + 1)
dp(0) = 1
for {
coin <- coins
i <- coin to amount
} dp(i) += dp(i - coin)
dp(n)
}
when I’m executing above method, I’m getting following error.
java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
at Main$.$anonfun$change$2(HelloWorld.scala:9)
But, when I Initialize the Array with new keyword(as following) and execute it, It is executing perfectly and I’m getting correct output.
Why?
def change(amount: Int, coins: Array[Int]): Int = {
val dp = new Array[Int](amount + 1)
dp(0) = 1
for {
coin <- coins
i <- coin to amount
} dp(i) += dp(i - coin)
dp(n)
}
I don’t know whether my understanding is correct or not, but only difference I found is mentioning new keyword. so my ask is, is there any connection to Array Initialization to get the ArrayIndexOutOfBoundExeption in the above methods, if yes, what is it?
I need Explanation in terms of Scala Programming.