Given an array, we need to modify values of this array in such a way that sum of absolute differences between two consecutive elements is maximized. If the value of an array element is X, then we can change it to either 1 or X.
Input : arr = [3, 2, 1, 4, 5] Output : 8 We can modify above array as, Modified arr = [3, 1, 1, 4, 1] Sum of differences = |1-3| + |1-1| + |4-1| + |1-4| = 8 Which is the maximum obtainable value among all choices of modification. Input : arr = [1, 8, 9] Output : 14
This problem is a variation of Assembly Line Scheduling and can be solved using dynamic programming. We need to maximize sum of differences each value X should be changed to either 1 or X. To achieve above stated condition we take a dp array of array length size with 2 columns, where dp[i] stores the maximum value of sum using first i elements only if ith array value is modified to 1 and dp[i] stores the maximum value of sum using first i elements if ith array value is kept as a[i] itself.Main thing to observe is,
Time Complexity : O(N)
Auxiliary Space : O(N)
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Minimum insertions to sort an array
- Maximum sum such that no two elements are adjacent
- Find minimum possible size of array with given rules for removing elements
- Ways to arrange Balls such that adjacent balls are of different types
- Maximize arr[j] - arr[i] + arr[l] - arr[k], such that i < j < k < l
- Find minimum adjustment cost of an array
- Find all distinct subset (or subsequence) sums of an array
- Minimum number of elements which are not part of Increasing or decreasing subsequence in array
- Count of AP (Arithmetic Progression) Subsequences in an array
- Minimum Sum Path In 3-D Array
- Size of array after repeated deletion of LIS
- Count binary strings with k times appearing adjacent two set bits
- Smallest length string with repeated replacement of two distinct adjacent
- Count of arrays in which all adjacent elements are such that one of them divide the another
- Clustering/Partitioning an array such that sum of square differences is minimum