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;
};
undefinedif you go outside the bounds, not an exceptiongo:while(go < len && prices[go] > prices[go-1])