The problem description:
Given an ArrayList
of Integers
. Find a subarray with the maximum sum of any potential subarray within the ArrayList
.
A subarray a is a combination of consecutive numbers.
The subarray can be of any length n
, where the size of n >= 0
.
Example
Input:
[-1, 10, -11, -1, 17, 0, 0, 9, 20, 7, -8, -6, -18]
Solution
[17, 0, 0, 9, 20, 0, 7]
Here is the code that I have so far.
public class MaxSubArray {
public ArrayList<Integer> solution(ArrayList<Integer> nums) {
int maxSubArrSum = Integer.MIN_VALUE;
int greatest = Integer.MAX_VALUE;
int smallest = 0;
int start;
int end;
ArrayList<Integer> maxSubArr;
ArrayList<ArrayList<Integer>> lists = new ArrayList();
try {
for (int left = 0; left < nums.size(); left++) {
int runningSum = 0;
for (int right = left; right < nums.size(); right++) {
runningSum += nums.get(right);
if (runningSum >= maxSubArrSum) {
ArrayList<Integer> temp = new ArrayList<>();
maxSubArrSum = runningSum;
start = left;
end = right;
for (int i = start; i <= end; i++) {
temp.add(nums.get(i));
}
lists.add(temp);
}
}
}
for (int i = 0; i < lists.size(); i++) {
if (lists.get(i).size() < greatest) {
greatest = lists.get(i).size();
smallest = i;
}
}
maxSubArr = lists.get(smallest);
return maxSubArr;
} catch (Exception e) {
e.printStackTrace();
return nums;
}
}
}
I am trying to iterate through the nums
ArrayList
and figuring out the first and last indexes of the subarrays with the maximum sum and putting them in a list of ArrayList
s.
After that, I am trying to figure out which of the subarrays has the smallest size and returning it.
What I am doing wrong here?