I am trying to return the maximum value in the subarray at index idx and return 0 if index is invalid or if sub array is empty. I have been working on passing this test for a while but I can't seem to do it and I don't know what is wrong with the code.
I'm not sure why you use 2d arrays. I guess that's why you can't get it working.
Here's a solution that works with simple 1d arrays:
static int[] data = new int[] { 1, 4, 2, 3 };
public static int subsetMax(int idx) {
if(idx >= data.length || idx < 0) {
return 0;
}
int max = 0;
// get the subarray from `idx` til the end of the array
int[] subarray = Arrays.copyOfRange(data, idx, data.length);
// for each element in the subarray:
// check if it is greater than the previous max value
for(int elem : subarray) {
max = Math.max(max, elem);
}
return max;
}
public static void main(String[] args) {
System.out.println(subsetMax(-1)); // 0
System.out.println(subsetMax(0)); // 4
System.out.println(subsetMax(1)); // 4
System.out.println(subsetMax(2)); // 3
System.out.println(subsetMax(3)); // 3
System.out.println(subsetMax(4)); // 0
}
From the example you provided it seems you are returning array of values.
public static List<Integer> subsetMax(int idx) {
if(idx >= data.length || idx < 0) {
return 0;
}
int max = 0;
List<Integer>max_values=new ArrayList<>();
for(int i = 0; i < data.length; i++) {
max = data[i][0];
for (int j = 0; j < data[i].length; j++) {
if(data[i][j]>max) {
max = data[i][j];
}
}
max_values.add(max);
}
return max_values;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.