"Blue Bridge Cup" Building Blocks Contest

building block contest

topic description

Chunchun Kindergarten held the annual "Building Blocks Contest". The content of this year's competition is to build a building with a width of n. The building can be regarded as composed of n blocks with a width of 1. The final height of the i-th block needs to be h_i.

Before the building starts, there are no blocks (it can be regarded as n blocks with a height of 0). For each subsequent operation, children can select a continuous interval [L, R], and then increase the heights of all blocks between the L block and the R block (including the L block and the R block) by 1.

Little M is a clever little friend, and she quickly figured out the best strategy to build the building so that the number of operations required for construction is the least. But she is not a child who is diligent in doing things, so I would like to ask you to help implement this strategy and find the least number of operations.

enter description

The input consists of two lines, the first line contains an integer n denoting the width of the building.

The second line contains n integers, the i-th integer being h_i.

Guarantee that 1 ≤ n ≤ 1 0 5 1 \leq n \leq 10^51n105 0 ≤ h i ≤ 1 0 4 0 \leq hi \leq 10^4 0hi104

output description

Output is only one line, the minimum number of operations required to build.

sample

#1

5
2 3 4 1 2
5

hint

analyze

1647349502732

Narrow down the scope and observe two buildings, for example, the first two buildings. If the i-th column is larger than the i-1-th column, it means that the i-th building has already covered the i-th building together when building the building, so the i-th Building i only needs to cover A[i] - A[i - 1] floors.

We can build an array of prefix differences: [ 2 , 1 , 1 , − 3 , 1 ] [2, 1, 1, -3, 1][2,1,1,3,1 ] Just add up the non-zero values.

AC Code

public static void main(String[] args) throws Exception {
    
    
    int n = nextInt();
    int[] A = new int[100005];
    int[] B = new int[100005];
    int ans = 0;
    for(int i = 1; i <= n; i++) A[i] = nextInt();
    for(int i = 1; i <= n; i++) {
    
    
        B[i] = A[i] - A[i - 1];
        if(B[i] > 0) ans += B[i];
    }
    System.out.println(ans);
}
public static void main(String[] args) throws Exception {
    
    
    int n = nextInt();
    int[] A = new int[100005];
    int ans = 0;
    for(int i = 1; i <= n; i++) {
    
    
        A[i] = nextInt();
        if(A[i] > A[i - 1]) ans += A[i] - A[i - 1];
    }
    System.out.println(ans);
}

Guess you like

Origin blog.csdn.net/qq_43098197/article/details/130484143