[NIO Automobile] NIO 20220713 Topic 3 - Travel Planning <Simulation, Sliding Window>

[NIO Automobile] NIO 20220713 Question 3 - Travel Planning

  Niu Niu has planned the tourism situation of n cities. It is known that each city has two attributes x and y, where x represents the cost of going to the i-th city, and y represents the happiness value that will be obtained after visiting the i-th city.
  Now Niu Niu wants to select some cities to visit, but the selected cities must satisfy that the absolute value of the cost difference between any two cities is less than k. Please help him
  calculate the maximum happiness value that can be obtained under the above conditions. How many

Input description:
Enter two integers n and k
on the first row, and enter two integers x and y in each line, which respectively represent the two attributes of each city
1 < n <= 100000
1 < k <= 1000000000
0 < x,y <= 1000000000

Output description:
output an integer to represent the answer

Example input:

5 3
1 3
2 1
5 2
3 1
4 3

Example output:

6

answer

Simulation: First arrange the order according to the size of x, and then find the continuous interval of the maximum value

public class Solution {
    
    
    public static void main(String[] args) {
    
    
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int k = in.nextInt();

        int[][] cities = new int[n][2];
        for (int i = 0; i < n; i++) {
    
    
            cities[i][0] = in.nextInt();
            cities[i][1] = in.nextInt();
        }
        Arrays.sort(cities, (a, b) -> a[0] - b[0]);

        int maxHappy = 0;
        int curHappy = 0;
        
        
        /* 
        //滑动窗口解法
        for(int i=0,j=0; i<n; i++){
            //当前的Happy值
            curHappy += cities[i][1];

            while (j<=i && cities[i][0]-cities[j][0] >=k){
                curHappy -= cities[j][1];
                j++;
            }
            maxHappy = Math.max(maxHappy,curHappy);
        }*/
        
        for (int i = 0; i < n; i++) {
    
    
            int j = i + 1;
            //当前的Happy值
            curHappy = cities[i][1];

            while (j < n && cities[j][0] - cities[i][0] < k) {
    
    
                curHappy += cities[j][1];
                j++;
            }
            maxHappy = Math.max(maxHappy, curHappy);
        }
        System.out.println(maxHappy);
    }
}

Guess you like

Origin blog.csdn.net/qq_44033208/article/details/132458999