forked from anitaa1990/Android-Cheat-sheet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSumSubsequenceOfNonadjacentElements.java
More file actions
36 lines (28 loc) · 1020 Bytes
/
MaxSumSubsequenceOfNonadjacentElements.java
File metadata and controls
36 lines (28 loc) · 1020 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package dynamicprogramming;
public class MaxSumSubsequenceOfNonadjacentElements {
/*
* Find an efficient algorithm to find maximum sum of a subsequence in an array such that no consecutive elements are part of this subsequence.
* Input: {1, 6, 10, 14, -5, -1, 2, -1, 3}
* Output: 25 i.e {4, -1, -2, 1, 5}
*
* Below solution has:
* Runtime Complexity - Linear, O(n).
* Memory Complexity - Linear, O(n).
*
* */
public static int getLargestSumFromArray(int[] arr) {
int[] result = new int[arr.length];
result[0] = arr[0];
for(int i=1; i<arr.length; i++) {
result[i] = Math.max(arr[i], result[i-1]);
if(i-2 >= 0) {
result[i] = Math.max(result[i], arr[i]+result[i-2]);
}
}
return result[arr.length-1];
}
public static void main(String[] args) {
int[] arr = {1, 6, 10, 14, -5, -1, 2, -1, 3};
System.out.println(getLargestSumFromArray(arr));
}
}