-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path4th_January.java
More file actions
29 lines (29 loc) · 870 Bytes
/
Copy path4th_January.java
File metadata and controls
29 lines (29 loc) · 870 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
class Solution {
public static int maximum_profit(int n, int[][] arr) {
// code here
Arrays.sort(arr,(a,b)->{
if(a[0]!=b[0]) return a[0]-b[0];
return a[1]-b[1];
});
int[]dp=new int[n];
return rec(0,arr,n,dp);
}
static int rec(int index,int[][]arr,int n,int[]dp){
if(index>=n)return 0;
if(dp[index]!=0)return dp[index];
int not_select=rec(index+1,arr,n,dp);
int nextIndex = findNext(index+1,arr[index][1],arr,n);
int select = arr[index][2] + rec(nextIndex,arr,n,dp);
return dp[index]=Math.max(select,not_select);
}
static int findNext(int i,int prevEnd,int[][]arr,int n){
while(i<n){
if(arr[i][0]>=prevEnd){
break;
}else{
i++;
}
}
return i;
}
}