Last active
September 20, 2019 09:47
-
-
Save indranil32/cdfdafcef163a37cbbee6666b002ad84 to your computer and use it in GitHub Desktop.
Dynamic Programming Samples
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
// max sum of non-consecutive numbers | |
def arr = [3, 1, 4, 2, 5, 10 ] | |
//def arr = [4,1,1,4,2,1] | |
//def arr = [2,5,3,1,7] | |
def map = [:] | |
// non dynamic solution - brute force | |
for (int i = 0 ; i < arr.size() ; i++) { | |
def sum = arr[i] | |
def op = [arr[i]] | |
for (int j = 0 ; j < arr.size() ; ) { | |
if(i==j || i-1 ==j || i+1==j){ | |
j++ | |
continue; | |
} | |
sum +=arr[j] | |
op.add(arr[j]) | |
j+=2 | |
} | |
map[sum] = op | |
println map | |
} | |
// the highest key in Map will have the non-consecutive sequence with max sum |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment