Created
October 3, 2020 13:55
-
-
Save ChrisLeNeve/b7a906cbccb7e971fe8236e265b84175 to your computer and use it in GitHub Desktop.
Max Array Sum from HackerRank (passes all test cases)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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