Skip to content

Instantly share code, notes, and snippets.

@ChrisLeNeve
Created October 3, 2020 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisLeNeve/b7a906cbccb7e971fe8236e265b84175 to your computer and use it in GitHub Desktop.
Save ChrisLeNeve/b7a906cbccb7e971fe8236e265b84175 to your computer and use it in GitHub Desktop.
Max Array Sum from HackerRank (passes all test cases)
class Scratch {
public static void main(String[] args) {
System.out.println(maxSubsetSum(new int[] {-2, 1, 3, -4, 5}));
}
static int maxSubsetSum (int[] arr){
if (arr.length == 0) {
return 0;
}
if (arr.length == 1) {
return arr[0];
}
int currentGreatest = Math.max(arr[0], arr[1]);
int[] maxValueAtEachIndex = new int[arr.length];
maxValueAtEachIndex[0] = arr[0];
maxValueAtEachIndex[1] = arr[1];
for (int i = 2; i < arr.length; i++) {
int currentValue = arr[i];
int maxAtPreviousIndex = maxValueAtEachIndex[i - 1];
int maxAtTwoPlacesBeforeWithCurrent = maxValueAtEachIndex[i - 2] + currentValue;
if (currentValue >= maxAtPreviousIndex && currentValue >= maxAtTwoPlacesBeforeWithCurrent) {
maxValueAtEachIndex[i] = currentValue;
currentGreatest = currentValue;
} else if (maxAtPreviousIndex >= currentValue && maxAtPreviousIndex >= maxAtTwoPlacesBeforeWithCurrent) {
maxValueAtEachIndex[i] = maxAtPreviousIndex;
currentGreatest = maxAtPreviousIndex;
} else {
maxValueAtEachIndex[i] = maxAtTwoPlacesBeforeWithCurrent;
currentGreatest = maxAtTwoPlacesBeforeWithCurrent;
}
}
return currentGreatest;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment