CLOSE
🛠️ Settings

Problem Statement

Given a circular array nums, find the maximum absolute difference between adjacent elements.

Note: In a circular array, the first and last elements are adjacent.

LeetCode Links

3423. Maximum Difference Between Adjacent Elements in a Circular Array

Constraints

  • 2 <= nums.length <= 100
  • -100 <= nums[i] <= 100

Examples

Example 1:

Input: nums = [1, 2, 4]
Output: 3

Explanation: Because nums is circular, nums[0] and nums[2] are adjacent. They have the maximum absolute difference of |4 - 1| = 3.

Example 2:

Input: nums = [-5,-10,-5]
Output: 5

Explanation:
The adjacent elements nums[0] and nums[1] have the maximum absolute difference of |-5 - (-10)| = 5.

Different Approaches

1️⃣ Brute Force Approach

Loop through the array and compute the absolute difference between every adjacent element (including last and first). Track the maximum.

Algorithm:

  1. Initialize maxDiff = 0.
  2. Loop through array with index i.
  3. Get diff = abs(nums[i] - nums[(i+1) % n])
  4. Update maxDiff accordingly.

Code:

#include <iostream>
#include <vector>
#include <cstdlib> // for abs()

using namespace std;

int maxAdjacentDifferenceCircular(vector<int>& nums) {
    int n = nums.size();
    int maxDiff = 0;

    for (int i = 0; i < n; ++i) {
        int nextIndex = (i + 1) % n;
        int diff = abs(nums[i] - nums[nextIndex]);
        maxDiff = max(maxDiff, diff);
    }

    return maxDiff;
}

int main() {
    vector<int> nums = {10, 12, 14, 1, 7};
    cout << "Maximum difference: " << maxAdjacentDifferenceCircular(nums) << endl;
    return 0;
}

Complexity Analysis:

  • Time Complexity:O(n)
    • As we are traversing the whole array once.
  • Space Complexity:O(1)
    • We are not using extra space.