LeetCode-in-Java

4020. Elevator Requests I

Easy

You are given an integer n denoting the number of floors in a building, where the floors are numbered from 0 to n - 1.

You are also given an integer array requests, where requests represents the sequence of floor requests.

An elevator starts at floor 0 and follows these rules:

Return the total time in seconds required to serve all requests.

Example 1:

Input: n = 5, requests = [2,1,4,3]

Output: 7

Explanation:

The total time required is 2 + 1 + 3 + 1 = 7 seconds.

Example 2:

Input: n = 3, requests = [2,0,0]

Output: 4

Explanation:

The total time required is 2 + 2 + 0 = 4 seconds.

Constraints:

Solution

@SuppressWarnings("java:S1172")
public class Solution {
    public int elevatorRequests(int n, int[] requests) {
        int time = requests[0];
        for (int i = 1; i < requests.length; i++) {
            int currDiff = Math.abs(requests[i] - requests[i - 1]);
            time += currDiff;
        }
        return time;
    }
}