What would be the fastest way to find the maximum of n elements within an array. (They don't need to be consecutive)
Eg a={1 ,3, 2, 5, 0, 10}
maximum sum when n=2 will be 15
Eg if
- n was 2 then we would use two loops
- n was 3 we would use 3 loops but that would be O(n^3).
then for n = 4, 5 ... the solution becomes very hard to find iteratively
I thought recursion could present a solution for this so I came up with
long rec(ArrayList<Int> a, int i, int n) {
if (i > 0 && i< n) {
return Math.max(a.get(i), rec(a, i-1, m)+ a.get(i));
} else {
return a.get(0);
}
}
called by
for(int i = a.size() -1; i >=n; i--) {
long max = rec(a,i,n);
}
But I can't seem to see a solution. Any suggestions on possible algorithms or approaches? Thanks