Created
October 2, 2014 00:53
-
-
Save jimexist/3fc9d70ea6834df42b21 to your computer and use it in GitHub Desktop.
BadNeighbors
This file contains hidden or 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
| public class BadNeighbors { | |
| public static void main(String[] args) { | |
| int[] collections = new int[args.length]; | |
| for (int i=0; i<args.length; ++i) { | |
| collections[i] = Integer.parseInt(args[i]); | |
| } | |
| System.out.printf("%d\n", maxDonations(collections)); | |
| } | |
| public static int maxDonations(int[] donations) { | |
| final int n = donations.length; | |
| if (n == 0) return 0; | |
| if (n == 1) return donations[0]; | |
| if (n == 2) return Math.max(donations[0], donations[1]); | |
| int[] zero = new int[n]; | |
| int[] one = new int[n]; | |
| zero[0] = donations[0]; | |
| zero[1] = Math.max(donations[1], donations[0]); | |
| one[0] = 0; | |
| one[1] = donations[1]; | |
| for (int i=2; i+1<n; ++i) { | |
| zero[i] = Math.max(zero[i-1], zero[i-2] + donations[i]); | |
| one[i] = Math.max(one[i-1], one[i-2] + donations[i]); | |
| } | |
| zero[n-1] = zero[n-2]; | |
| one[n-1] = Math.max(one[n-3] + donations[n - 1], one[n-2]); | |
| return Math.max(zero[n-1], one[n-1]); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment