Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Solution {
- public ArrayList<Integer> maxset(ArrayList<Integer> a) {
- boolean positiveValueExists = false;
- int maxValue = Integer.MIN_VALUE;
- for (int e : a) {
- if (e >= 0) {
- positiveValueExists = true;
- break;
- }
- maxValue = Math.max(e, maxValue);
- }
- ArrayList<Integer> solution = new ArrayList<Integer>();
- if (!positiveValueExists) {
- solution.add(maxValue);
- return solution;
- }
- int maxSum = 0;
- int maxSolutionLength = 0;
- int maxSolutionStartingIndex = 0;
- int sum = 0;
- int solutionLength = 0;
- int startingIndex = 0;
- for (int i = 0; i < a.size(); i++) {
- int e = a.get(i);
- sum += e;
- solutionLength++;
- if (sum < 0) {
- sum = 0;
- solutionLength = 0;
- startingIndex = i + 1;
- }
- else {
- if (sum > maxSum || (sum == maxSum && solutionLength > maxSolutionLength)) {
- maxSum = sum;
- maxSolutionLength = solutionLength;
- maxSolutionStartingIndex = startingIndex;
- }
- }
- }
- return new ArrayList<Integer>(a.subList(maxSolutionStartingIndex,
- maxSolutionStartingIndex + maxSolutionLength));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment