Q10 Maximum sum increasing subsequence | Practice | GeeksforGeeks

PHOTO EMBED

Thu Mar 02 2023 09:09:54 GMT+0000 (Coordinated Universal Time)

Saved by @Ayush_dabas07

//{ Driver Code Starts
//Initial Template for Java

import java.io.*;
import java.util.*;
class GfG
{
    public static void main(String args[])
        {
            Scanner sc = new Scanner(System.in);
            int t = sc.nextInt();
            while(t-->0)
                {
                    int n = sc.nextInt();
                    int Arr[] = new int[n];
                    for(int i = 0;i<n;i++)
                        Arr[i] = sc.nextInt();
                    Solution ob = new Solution();
                    System.out.println(ob.maxSumIS(Arr,n));
                }
        }
}    
// } Driver Code Ends


//User function Template for Java

class Solution
{
	public int maxSumIS(int arr[], int n)  
	{  
	        /* storage - 1d array , meaning - every cell will store maximum LIS sum ending at that
	    element(inclusive)
	    */
	    //base case
	    if(n == 1)return arr[0];
	    
	    int dp[] = new int[n];
	    dp[0] = arr[0]; //for length 1 max LIS will be that element
	    
	    int ans = dp[0];
	    
	    for(int i = 1 ; i< n ;i++){
	        
	        for(int j = i-1 ; j>= 0 ; j--){
//storing maximum LIS sum of previous elements provided the element is smaller than current
	            if(arr[j] < arr[i])
	            dp[i] = Math.max(dp[i],dp[j]);
	    }
	    //now adding current elements value to the max LIS
	    dp[i] += arr[i];
	    
	    ans = Math.max(dp[i],ans);
	}  
	
	return ans;
	}  
}
content_copyCOPY

https://practice.geeksforgeeks.org/problems/maximum-sum-increasing-subsequence4749/1