We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Maximum Difference Between Adjacent Elements in a Circular Array

Number: 3747

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given a circular array of integers, compute the maximum absolute difference between any two adjacent elements. Since the array is circular, the first and last elements are also considered adjacent.


Key Insights

  • Treat the array as circular so that the last element is adjacent to the first element.
  • Iterate through the array, computing the absolute difference between each pair of adjacent elements.
  • Use modulo arithmetic (i.e., (i+1) % n) to wrap around for the last element.
  • Track and update the maximum encountered difference.

Space and Time Complexity

Time Complexity: O(n), where n is the number of elements in the array, since we traverse the array once. Space Complexity: O(1), as we only use a few extra variables regardless of the input size.


Solution

The approach is straightforward:

  1. Iterate over each index in the array.
  2. Compute the absolute difference between the current element and the next element, with the next element calculated using modulo arithmetic to handle the circular condition.
  3. Maintain a variable to track the maximum difference found.
  4. Return the maximum difference after processing the entire array.

This algorithm uses simple iteration and modulo indexing to efficiently solve the problem.


Code Solutions

# Function to compute the maximum absolute difference between adjacent elements in a circular array
def max_adjacent_difference(nums):
    # Calculate the number of elements in the array
    n = len(nums)
    # Initialize max_diff to track the maximum adjacent difference
    max_diff = 0
    # Traverse the array
    for i in range(n):
        # Use modulo to access the circular adjacent element
        diff = abs(nums[i] - nums[(i + 1) % n])
        # Update max_diff if current difference is greater
        max_diff = max(max_diff, diff)
    return max_diff

# Example usage:
print(max_adjacent_difference([1, 2, 4]))  # Expected output: 3
print(max_adjacent_difference([-5, -10, -5]))  # Expected output: 5
← Back to All Questions