MuhammadTausif / gfg-excercises

This repo is about exercises at GFG
Apache License 2.0
0 stars 0 forks source link

Swap and Maximize - POTD | 1-Nov-2024 #63

Closed MuhammadTausif closed 4 hours ago

MuhammadTausif commented 4 hours ago

Swap and Maximize

Link

Difficulty: Easy

Given an array arr[ ] of positive elements. Consider the array as a circular array, meaning the element after the last element is the first element of the array. The task is to find the maximum sum of the absolute differences between consecutive elements with shuffling of array elements allowed i.e. shuffle the array elements and make [a1..an] such order that |a1 – a2| + |a2 – a3| + …… + |an-1 – an| + |an – a1| is maximized.

Examples:

Input: arr[] = [4, 2, 1, 8]
Output: 18
Explanation: After Shuffling, we get [1, 8, 2, 4]. Sum of absolute difference between consecutive elements after rearrangement = |1 - 8| + |8 - 2| + |2 - 4| + |4 - 1| = 7 + 6 + 2 + 3 = 18.
Input: arr[] = [10, 12]
Output: 4
Explanation: No need of rearrangement. Sum of absolute difference between consecutive elements = |10 - 12| + |12 - 10| = 2 + 2 = 4.

Constraints:

MuhammadTausif commented 4 hours ago

Solved

arr.sort()
l=[]
i=0
j=len(arr)-1
while(i<j):
    l.append(arr[i])
    l.append(arr[j])
    i+=1 
    j-=1 
if i==j:
    l.append(arr[i])
s=0
for i in range(len(l)-1):
    s+=abs(l[i]-l[i+1])
s+=abs(l[0]-l[-1])
return s