Reputation: 182
Here's my Java code:
class Solution {
public int maxProfit(int[] prices) {
int profit = 0;
int i = 0;
int len = prices.length;
while(i < len){
int go = i + 1;
while(prices[go] > prices[go-1]){
go++;
}
profit += Math.abs(prices[i] - prices[go-1]);
i = go;
}
return profit;
}
}
I wrote a function in JS with the same logic and it worked fine, but running the above Java code with input
[2,3,4,6,3,9]
gives me the error "java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6"
Why?
P.S. My JavaScript function is:
var maxProfit = function(prices) {
let profit = 0;
let i = 0;
let len = prices.length;
while(i < len){
let go = i+1
while(prices[go] > prices[go-1]){
go++;
}
profit += Math.abs(prices[i] - prices[go-1])
i = go
}
return profit;
};
Upvotes: 2
Views: 93
Reputation: 76
This part of your code is where the out of bounds error is coming from:
int len = prices.length;
while(i < len){
int go = i + 1;
while(prices[go] > prices[go-1]){
go++;
}
As an example, if the prices
array had four elements in it, len
will be 4, but the maximum index you could use before getting out of bounds would be 3 (because the array is zero-indexed). You end up indexing prices with i
, which is fine because according to your while loop logic, i
will always be less than len
.
However, when you have int go = i + 1
and then prices[go]
, at some point i
will be the maximum index of the array and go
will be beyond that, throwing the out of bounds error.
So, why does JavaScript not throw the same error, and your code seemingly works?
JavaScript won't throw an error for an out of bounds index in an array, instead prices[go]
will evaluate to undefined
. (undefined > prices[go - 1])
will then evaluate to false, stopping your while loop, and execution continues.
If you would like your Java snippet to work the same as the JavaScript one, you could change your while loop condition to while(go < len && prices[go] > prices[go - 1])
.
Upvotes: 1
Reputation: 2976
Change your Java conditional to
while(go < len && prices[go] > prices[go - 1])
to prevent an undefined index from being called
Upvotes: 2
Reputation: 355
Javascript works in the following way: Say, lets have an array of length N, then arr[X]>arr[Y] where X>=N and 0<=Y<N returns false instead of indexoutofbound exception. Here arr[X] returns undefined so it will be undefined > arr[Y]. So its breaking the loop and you are getting the output correct.
Upvotes: 1