Skip to content

Commit a042c3a

Browse files
authored
maximum sum increasing subsequence dp problem in Java
1 parent a882ac0 commit a042c3a

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import java.util.Scanner;
2+
3+
public class MaximumSumIncreasingSubsequence {
4+
public static int MaximumSumIncreasingSubsequence(int[] A, int n) {
5+
int max = 0;
6+
int dp[] = new int[n];
7+
8+
for (int i = 0; i < n; i++) {
9+
dp[i] = A[i];
10+
}
11+
12+
for (int i = 1; i < n; i++) {
13+
for (int j = 0; j < i; j++) {
14+
if (dp[i] < dp[j] + A[i] && A[i] > A[j]) {
15+
dp[i] = dp[j] + A[i];
16+
}
17+
}
18+
}
19+
20+
for (int i = 0; i < n; i++) {
21+
if (dp[i] > max) {
22+
max = dp[i];
23+
}
24+
}
25+
26+
return max;
27+
}
28+
29+
public static void main(String[] args) {
30+
//Dynamic Programming approach
31+
Scanner sc = new Scanner(System.in);
32+
33+
int n = sc.nextInt();
34+
int[] A = new int[n];
35+
36+
for (int i = 0; i < n; i++) {
37+
A[i] = sc.nextInt();
38+
}
39+
40+
System.out.println(MaximumSumIncreasingSubsequence(A, n));
41+
}
42+
}

0 commit comments

Comments
 (0)