Stack Overflow Asked by Tzvi2 on December 5, 2021
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;
};
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])
.
Answered by tyler-tm on December 5, 2021
Change your Java conditional to
while(go < len && prices[go] > prices[go - 1])
to prevent an undefined index from being called
Answered by Pavlos Karalis on December 5, 2021
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.
Answered by Gopi krishna on December 5, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP