Maximize difference of integers in a subarray of size K
Given an array arr[] of length N, the task is to find the maximum difference of integers in a subarray of size K.
Input: arr = [2, 3, -1, -5, 4, 0], K = 3
Output: 9
Explanation: Subarray [-1, -5, 4] contains the maximum difference between -5 and -4 as 9
Input: arr = [-2, -4, 0, 1, 5, -6, 9], K =4
Output: 15
Explanation: Subarray [1, 5, -6, 9] contains the maximum difference between -6 and 9 as 15
Approach: The given problem can be solved using the two-pointers technique and the sliding window approach with TreeMap data structure. Below steps can be followed to solve the problem:
- Iterate the array arr till K – 1 and insert the elements in the TreeMap,
- If the integer is already present in the TreeMap, then increase its frequency by 1
- Iterate the array arr from K till the end of the array using a pointer right and at every iteration:
- Insert the element in the TreeMap, if it does not exist or else increase its frequency by 1
- Remove the leftmost element of the sliding window if its frequency is one, or else reduce its frequency by 1
- Calculate the difference between maximum and minimum elements by retrieving the first and last element from the treeMap, and also update the result res
- Return the result res
C++
#include <bits/stdc++.h>
using namespace std;
int maxDiffK(
vector< int > arr, int K)
{
int N = arr.size();
map< int , int > tm ;
for ( int i = 0; i < K; i++)
{
int f = tm [arr[i]];
if (f == 0)
{
tm [arr[i]] = 1;
}
else
{
tm [arr[i]] = f + 1;
}
}
int maxDiff = abs (
tm .begin()->first - tm .rbegin()->first);
for ( int i = K; i < N; i++)
{
int f = tm [arr[i]];
if (f == 0)
{
tm [arr[i]] = 1;
}
else
{
tm [arr[i]] = f + 1;
}
int freq = tm [arr[i - K]];
if (freq == 1)
tm .erase( tm .find(arr[i - K]));
else
tm [arr[i - K]] = freq - 1;
maxDiff = max(
maxDiff,
abs (
tm .begin()->first - tm .rbegin()->first));
}
return maxDiff;
}
int main()
{
vector< int > arr = {2, 3, -1, -5, 4, 0};
int K = 3;
cout << (maxDiffK(arr, K));
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static int maxDiffK(
int arr[], int K)
{
int N = arr.length;
TreeMap<Integer, Integer> tm
= new TreeMap<>();
for ( int i = 0 ; i < K; i++) {
Integer f = tm.get(arr[i]);
if (f == null ) {
tm.put(arr[i], 1 );
}
else {
tm.put(arr[i], f + 1 );
}
}
int maxDiff = Math.abs(
tm.firstKey() - tm.lastKey());
for ( int i = K; i < N; i++) {
Integer f = tm.get(arr[i]);
if (f == null ) {
tm.put(arr[i], 1 );
}
else {
tm.put(arr[i], f + 1 );
}
int freq = tm.get(arr[i - K]);
if (freq == 1 )
tm.remove(arr[i - K]);
else
tm.put(arr[i - K], freq - 1 );
maxDiff = Math.max(
maxDiff,
Math.abs(
tm.firstKey()
- tm.lastKey()));
}
return maxDiff;
}
public static void main(String[] args)
{
int [] arr = { 2 , 3 , - 1 , - 5 , 4 , 0 };
int K = 3 ;
System.out.println(maxDiffK(arr, K));
}
}
|
Python3
def maxDiffK(arr, K):
N = len (arr)
tm = {}
for i in range ( 0 , K):
if ( not (arr[i] in tm)):
tm[arr[i]] = 1
else :
tm[arr[i]] + = 1
maxDiff = max ( list (tm)) - min ( list (tm))
for i in range (K, N):
if ( not (arr[i] in tm)):
tm[arr[i]] = 1
else :
tm[arr[i]] + = 1
freq = tm[arr[i - K]]
if (freq = = 1 ):
del tm[arr[i - K]]
else :
tm[arr[i - K]] - = 1
maxDiff = max (maxDiff, max ( list (tm)) - min ( list (tm)))
return maxDiff
if __name__ = = "__main__" :
arr = [ 2 , 3 , - 1 , - 5 , 4 , 0 ]
K = 3
print (maxDiffK(arr, K))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG
{
public static int maxDiffK( int [] arr, int K)
{
int N = arr.Length;
Dictionary< int , int > tm = new Dictionary< int , int >();
for ( int i = 0; i < K; i++)
{
if (!tm.ContainsKey(arr[i]))
{
tm[arr[i]] = 1;
}
else
{
tm[arr[i]] += 1;
}
}
int [] keys = tm.Keys.ToArray();
Array.Sort(keys);
int maxDiff = Math.Abs(keys.First() - keys.Last());
for ( int i = K; i < N; i++)
{
if (!tm.ContainsKey(arr[i]))
{
tm[arr[i]] = 1;
}
else
{
tm[arr[i]] += 1;
}
int freq = tm[arr[i - K]];
if (freq == 1)
tm.Remove(arr[i - K]);
else
tm[arr[i - K]] = freq - 1;
keys = tm.Keys.ToArray();
Array.Sort(keys);
maxDiff = Math.Max(maxDiff, Math.Abs(keys.First() - keys.Last()));
}
return maxDiff;
}
public static void Main()
{
int [] arr = { 2, 3, -1, -5, 4, 0 };
int K = 3;
Console.Write(maxDiffK(arr, K));
}
}
|
Javascript
<script>
function maxDiffK(arr, K) {
let N = arr.length;
let tm = new Map();
for (let i = 0; i < K; i++) {
let f = tm.get(arr[i]);
if (!f) {
tm.set(arr[i], 1);
}
else {
tm.set(arr[i], f + 1);
}
}
let maxDiff = Math.abs([...tm.keys()].sort((a, b) => a - b)[0] - [...tm.keys()].sort((a, b) => b - a)[0]);
for (let i = K; i < N; i++) {
let f = tm.get(arr[i]);
if (!f) {
tm.set(arr[i], 1);
}
else {
tm.set(arr[i], f + 1);
}
let freq = tm.get(arr[i - K]);
if (freq == 1)
tm. delete ((arr[i - K]));
else
tm.set(arr[i - K], freq - 1);
maxDiff = Math.max(
maxDiff,
Math.abs([...tm.keys()].sort((a, b) => a - b)[0] - [...tm.keys()].sort((a, b) => b - a)[0]));
}
return maxDiff;
}
let arr = [2, 3, -1, -5, 4, 0];
let K = 3;
document.write((maxDiffK(arr, K)))
</script>
|
Time Complexity: O(N * log K)
Auxiliary Space: O(N)
Last Updated :
23 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...