static ArrayList<Integer> subarraySum(int[] arr, int n, int s) {
// Your code here
int sum, i, j;
// Pick a starting point
for (i = 0; i < n; i++) {
sum = arr[i];
// try all subarrays starting with 'i'
for (j = i + 1; j <= n; j++) {
if (sum == s) {
int p = j - 1;
return new ArrayList[] { j, p };
}
if (sum > s || j == n)
break;
sum = sum + arr[j];
}
}
return -1;
}
The problem is Given an unsorted array A of size N that contains only non-negative integers, find a continuous sub-array that adds to a given number S. But I am unable to return the positions as ArrayList.
This code shows an error:
Compilation Error:
prog.java:45: error: incompatible types: int cannot be converted to ArrayList
return new ArrayList[] { j, p };
^
prog.java:45: error: incompatible types: int cannot be converted to ArrayList
return new ArrayList[] { j, p };
^
prog.java:45: error: incompatible types: ArrayList[] cannot be converted to ArrayList<Integer>
return new ArrayList[] { .................
class Subarray{
static ArrayList<Integer> subarraySum(int[] arr, int n, int s) {
// Your code here
ArrayList<Integer> a = new ArrayList<Integer>();
int sum, i, j;
// Pick a starting point
for (i = 0; i < n; i++) {
sum = arr[i];
// try all subarrays starting with 'i'
for (j = i + 1; j <= n; j++) {
if (sum == s) {
a.add(i+1);
a.add(j);
return a;
}
if (sum > s || j == n)
break;
sum = sum + arr[j];
}
}
a.add(-1);
return a;
}
}
The return value should be an ArrayList.