-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSubsetSum.java
More file actions
49 lines (48 loc) · 851 Bytes
/
MaxSubsetSum.java
File metadata and controls
49 lines (48 loc) · 851 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
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.*;
public class MaxSubsetSum {
public static int max(int a,int b,int c) {
if(a>=b) {
if(a>c) {
return a;
}
else {
return c;
}
}
else {
if(b>=c) {
return b;
}
else {
return c;
}
}
}
public static int MaxSum(int[] arr,int n) {
if(n<=2) {
return 0;
}
else {
int[] dp=new int[n];
dp[0]=arr[0];
dp[1]=Math.max(arr[0], arr[1]);
for(int i=2;i<n;i++) {
dp[i]=max(dp[i-1],arr[i],dp[i-2]+arr[i]);
}
System.out.println(Arrays.toString(dp));
return dp[n-1];
}
}
public static void main(String[] args) {
int[] arr;
int n;
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
arr=new int[n];
for(int i=0;i<n;i++) {
arr[i]=sc.nextInt();
}
System.out.println(MaxSum(arr,n));
sc.close();
}
}