PracticeArrays

Check a Shipment Loading Trend

Easy/MediumArraystraversalstate trackinginvariants Time not estimated Not started

Context

A warehouse records the weights of packages loaded onto one delivery vehicle. The loading record is considered orderly if package weights never decrease from one package to the next, or if they never increase. Equal neighboring weights are allowed.

Problem

Write a function that decides whether the package-weight record is monotonic in at least one direction. Return true if every adjacent pair is nondecreasing or every adjacent pair is nonincreasing; otherwise return false. An empty record and a record with one package are valid because they have no contradictory adjacent pair. Equal weights must preserve both possible directions. Scan the record once and use constant extra space.

Examples

Example 1
Input: weights = [2, 4, 4, 7]
Output: True
Explanation: For [2, 4, 4, 7], the final states are nondecreasing_ok=true and nonincreasing_ok=false, so the executed result is true.
Example 2
Input: weights = [10, 8, 5, 5, 1]
Output: True
Explanation: For [10, 8, 5, 5, 1], the final states are nondecreasing_ok=false and nonincreasing_ok=true, so the executed result is true.
Example 3
Input: weights = [3, 7, 4, 6]
Output: False
Explanation: For [3, 7, 4, 6], both final feasibility states are false, so the executed result is false.

Constraints

  • 0 <= len(weights) <= 100000
  • 0 <= weights[i] <= 1000000 for every i
  • Types: weights is int[]; result is bool

Function signature

def is_orderly_loading(weights: list[int]) -> bool
weights list[int]
Package weights in the order they were loaded.
returns bool
True when the weights are nondecreasing or nonincreasing, including records with equal neighboring values; otherwise false.

Adapted from MBPP problem task_68 (CC BY 4.0). Rewritten, extended and verified by Iksha.

Approved · cc002-abs_522_v114 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1