geeksforgeeks@ Maximum Index (Dynamic Programming)

Posted 流白

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了geeksforgeeks@ Maximum Index (Dynamic Programming)相关的知识,希望对你有一定的参考价值。

http://www.practice.geeksforgeeks.org/problem-page.php?pid=129

Maximum Index

Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j].

Example :

A : [3 5 4 2]

Output : 2 
for the pair (3, 4)

Input:

The first line contains an integer T, depicting total number of test cases. 
Then following T lines contains an integer N depicting the size of array and next line followed by the value of array.
Output:

Print the maximum difference of the indexes i and j in a separtate line.
Constraints:

1 ≤ T ≤ 30
1 ≤ N ≤ 1000
0 ≤ A[i] ≤ 100
Example:

Input
1
2
1 10
Output
1

 

import java.util.*;
import java.lang.*;
import java.io.*;

class GFG {
    
    public static int func(int[] arr) {
        
        int n = arr.length;
        int[] dp = new int[n];
        int rs = 0;
        
        dp[0] = 0;
        for(int i=1; i<n; ++i) {
            for(int pre=0; pre<i; ++pre) {
                if(arr[i] >= arr[pre]) {
                    dp[i] = Math.max(dp[i], dp[pre] + i - pre);
                    rs = Math.max(rs, dp[i]);
                }
            }
        }
        return rs;
    }
    
    public static void main (String[] args) {
        Scanner in = new Scanner(System.in);
        int times = in.nextInt();
        
        while(times > 0) {
            --times;
            
            int n = in.nextInt();
            int[] arr = new int[n];
            for(int i=0; i<n; ++i) {
                arr[i] = in.nextInt();
            }
            
            System.out.println(func(arr));
        }
    }
}
View Code

 

以上是关于geeksforgeeks@ Maximum Index (Dynamic Programming)的主要内容,如果未能解决你的问题,请参考以下文章

[GeeksForGeeks] Swap nodes in a single linked list by changing links

[GeeksForGeeks] Find the largest pair sum in an unsorted array

[GeeksForGeeks] Level order traversal in spiral form of a binary tree.

[GeeksForGeeks] Extract Leaves of a Binary Tree in a Doubly Linked List

[GeeksForGeeks] Populate inorder successor for all nodes in a binary search tree

[GeeksForGeeks] Count Number of ways to reach a given score in a game