medium
0 views

Increase By Adjacent Difference

Increment each number by the absolute difference between its adjacent cells, treating missing neighbors as zero.

Understand the Problem

Problem Statement

Given N numbers, the program must increment each number by the absolute difference between its adjacent cells. For the first and last numbers, treat the missing adjacent element as zero.

Constraints

  • 2 ≤ N ≤ 9999
  • -99999 ≤ Value of each number ≤ 99999

Examples

Example 1
Input
6
-20 10 55 -5 20 -10
Output
-10 85 70 30 25 10
Explanation
For first element (-20): -20 + abs(10) = -10
For second element (10): 10 + abs(55 - (-20)) = 10 + 75 = 85
For third element (55): 55 + abs(-5 - 10) = 55 + 15 = 70
For fourth element (-5): -5 + abs(20 - 55) = -5 + 35 = 30
For fifth element (20): 20 + abs(-10 - (-5)) = 20 + 5 = 25
For last element (-10): -10 + abs(20) = -10 + 20 = 10

Solution

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n;
    scanf("%d", &n);
    
    int a[n];
    for(int i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }
    
    // Create a copy to preserve original values
    int b[n];
    for(int i = 0; i < n; i++) {
        b[i] = a[i];
    }
    
    // Process each element
    for(int i = 0; i < n; i++) {
        if(i == 0) {
            // First element: add absolute value of next element
            a[i] = b[i] + abs(b[i + 1]);
        }
        else if(i == n - 1) {
            // Last element: add absolute value of previous element
            a[i] = b[i] + abs(b[i - 1]);
        }
        else {
            // Middle elements: add absolute difference between adjacent elements
            int diff = abs(b[i + 1] - b[i - 1]);
            a[i] += diff;
        }
    }
    
    // Output the result
    for(int i = 0; i < n; i++) {
        printf("%d ", a[i]);
    }
    
    return 0;
}
Time:O(n)
Space:O(n)
Approach:

C Solution Explanation:

  1. Input Reading: Read N and the array elements using scanf
  2. Array Copy: Create a copy of the original array to avoid modifying values during calculation
  3. Processing Logic:
    • For index 0: Add absolute value of the next element (a[1])
    • For index n-1: Add absolute value of the previous element (a[n-2])
    • For middle indices: Add absolute difference between next and previous elements
  4. Output: Print all modified values separated by spaces

Key Points: Uses abs() function from stdlib.h for absolute values, and preserves original values in a separate array to ensure correct calculations.

Visual Explanation

Loading diagram...