📜  最大化大小为 K 的子数组中的整数差

📅  最后修改于: 2022-05-13 01:56:08.220000             🧑  作者: Mango

最大化大小为 K 的子数组中的整数差

给定一个长度为N的数组arr[] ,任务是在一个大小为K的子数组中找到整数的最大差值。

方法:给定的问题可以使用双指针技术和具有 TreeMap 数据结构的滑动窗口方法来解决。可以按照以下步骤解决问题:

  • 迭代数组arr直到K - 1并将元素插入TreeMap,
    • 如果整数已经存在于TreeMap 中,则将其频率增加 1
  • 在每次迭代中使用指针right迭代数组arrK到数组末尾:
    • TreeMap 中插入元素,如果它不存在,否则将其频率增加 1
    • 如果滑动窗口的频率为 1,则删除其最左边的元素,否则将其频率减少 1
    • 通过从treeMap 中检索第一个和最后一个元素来计算最大和最小元素之间的差异,并更新结果res
  • 返回结果res
C++
// C++ code for the above approach
#include 
using namespace std;
 
// Function to find the
// maximum difference in integers
// of subarray of size K
int maxDiffK(
    vector arr, int K)
{
 
    // Initialize length of the array
    int N = arr.size();
 
    // Initialize a TreeMap
    map tm;
 
    // Iterate the array arr till K - 1
    for (int i = 0; i < K; i++)
    {
 
        // Get the frequency of the
        // arr[i] from the treemap
        int f = tm[arr[i]];
 
        // If freq is null
        if (f == 0)
        {
 
            // Add the integer in the
            // treemap with frequency 1
            tm[arr[i]] = 1;
        }
        else
        {
 
            // Increment the frequency
            // of the element
            tm[arr[i]] = f + 1;
        }
    }
 
    // Initialize MaxDiff to the absolute
    // Difference between greatest and
    // smallest element in the treemap
    int maxDiff = abs(
        tm.begin()->first - tm.rbegin()->first);
 
    // Iterate the array arr
    // from K till the end
    for (int i = K; i < N; i++)
    {
 
        // Get the frequency of the
        // current element from the treemap
        int f = tm[arr[i]];
 
        // If freq is null then add the
        // integer in the treemap
        // with frequency 1
        if (f == 0)
        {
 
            tm[arr[i]] = 1;
        }
        else
        {
 
            // Increment the frequency
            // of the element
            tm[arr[i]] = f + 1;
        }
 
        int freq = tm[arr[i - K]];
 
        // If freq is 1 then remove the
        // value from the treemap
        if (freq == 1)
            tm.erase(tm.find(arr[i - K]));
 
        // Else reduce the frequency
        // of that element by 1
        else
            tm[arr[i - K]] = freq - 1;
 
        // Update maxDiff with the maximum
        // of difference between smallest
        // and greatest element in treemap
        // and maxDiff
        maxDiff = max(
            maxDiff,
            abs(
                tm.begin()->first - tm.rbegin()->first));
    }
 
    // Return the answer as maxDiff
    return maxDiff;
}
 
// Driver code
int main()
{
 
    // Initialize the array
    vector arr = {2, 3, -1, -5, 4, 0};
 
    // Initialize the value of K
    int K = 3;
 
    // Call the function and
    // print the result
    cout << (maxDiffK(arr, K));
    return 0;
}
 
// This code is contributed by Potta Lokesh


Java
// Java implementation for the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to find the
    // maximum difference in integers
    // of subarray of size K
    public static int maxDiffK(
        int arr[], int K)
    {
 
        // Initialize length of the array
        int N = arr.length;
 
        // Initialize a TreeMap
        TreeMap tm
            = new TreeMap<>();
 
        // Iterate the array arr till K - 1
        for (int i = 0; i < K; i++) {
 
            // Get the frequency of the
            // arr[i] from the treemap
            Integer f = tm.get(arr[i]);
 
            // If freq is null
            if (f == null) {
 
                // Add the integer in the
                // treemap with frequency 1
                tm.put(arr[i], 1);
            }
            else {
 
                // Increment the frequency
                // of the element
                tm.put(arr[i], f + 1);
            }
        }
 
        // Initialize MaxDiff to the absolute
        // Difference between greatest and
        // smallest element in the treemap
        int maxDiff = Math.abs(
            tm.firstKey() - tm.lastKey());
 
        // Iterate the array arr
        // from K till the end
        for (int i = K; i < N; i++) {
 
            // Get the frequency of the
            // current element from the treemap
            Integer f = tm.get(arr[i]);
 
            // If freq is null then add the
            // integer in the treemap
            // with frequency 1
            if (f == null) {
 
                tm.put(arr[i], 1);
            }
            else {
 
                // Increment the frequency
                // of the element
                tm.put(arr[i], f + 1);
            }
 
            int freq = tm.get(arr[i - K]);
 
            // If freq is 1 then remove the
            // value from the treemap
            if (freq == 1)
                tm.remove(arr[i - K]);
 
            // Else reduce the frequency
            // of that element by 1
            else
                tm.put(arr[i - K], freq - 1);
 
            // Update maxDiff with the maximum
            // of difference between smallest
            // and greatest element in treemap
            // and maxDiff
            maxDiff = Math.max(
                maxDiff,
                Math.abs(
                    tm.firstKey()
                    - tm.lastKey()));
        }
 
        // Return the answer as maxDiff
        return maxDiff;
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        // Initialize the array
        int[] arr = { 2, 3, -1, -5, 4, 0 };
 
        // Initialize the value of K
        int K = 3;
 
        // Call the function and
        // print the result
        System.out.println(maxDiffK(arr, K));
    }
}


Python3
# python code for the above approach
 
# Function to find the
# maximum difference in integers
# of subarray of size K
def maxDiffK(arr, K):
 
    # Initialize length of the array
    N = len(arr)
 
    # Initialize a TreeMap
    tm = {}
 
    # Iterate the array arr till K - 1
    for i in range(0, K):
 
        # If freq is null
        if (not (arr[i] in tm)):
 
            # Add the integer in the
            # treemap with frequency 1
            tm[arr[i]] = 1
        else:
 
             # Increment the frequency
             # of the element
            tm[arr[i]] += 1
 
        # Initialize MaxDiff to the absolute
        # Difference between greatest and
        # smallest element in the treemap
    maxDiff = max(list(tm)) - min(list(tm))
 
    # Iterate the array arr
    # from K till the end
    for i in range(K, N):
 
         # If freq is null then add the
         # integer in the treemap
         # with frequency 1
        if (not (arr[i] in tm)):
            tm[arr[i]] = 1
 
        else:
 
             # Increment the frequency
             # of the element
            tm[arr[i]] += 1
 
        freq = tm[arr[i - K]]
 
        # If freq is 1 then remove the
        # value from the treemap
        if (freq == 1):
            del tm[arr[i - K]]
 
            # Else reduce the frequency
            # of that element by 1
        else:
            tm[arr[i - K]] -= 1
 
            # Update maxDiff with the maximum
            # of difference between smallest
            # and greatest element in treemap
            # and maxDiff
        maxDiff = max(maxDiff, max(list(tm)) - min(list(tm)))
 
    # Return the answer as maxDiff
    return maxDiff
 
# Driver code
if __name__ == "__main__":
   
    # Initialize the array
    arr = [2, 3, -1, -5, 4, 0]
 
    # Initialize the value of K
    K = 3
 
    # Call the function and
    # print the result
    print(maxDiffK(arr, K))
 
    # This code is contributed by rakeshsahni


C#
// C# implementation for the above approach
using System;
using System.Collections.Generic;
using System.Linq;
 
class GFG
{
 
    // Function to find the
    // maximum difference in ints
    // of subarray of size K
    public static int maxDiffK(int[] arr, int K)
    {
 
        // Initialize length of the array
        int N = arr.Length;
 
        // Initialize a TreeMap
        Dictionary tm = new Dictionary();
 
        // Iterate the array arr till K - 1
        for (int i = 0; i < K; i++)
        {
 
            // Get the frequency of the
            // arr[i] from the treemap
            if (!tm.ContainsKey(arr[i]))
            {
 
                // Add the int in the
                // treemap with frequency 1
                tm[arr[i]] = 1;
            }
            else
            {
 
                // Increment the frequency
                // of the element
                tm[arr[i]] += 1;
            }
        }
 
        // Initialize MaxDiff to the absolute
        // Difference between greatest and
        // smallest element in the treemap
        int[] keys = tm.Keys.ToArray();
        Array.Sort(keys);
        int maxDiff = Math.Abs(keys.First() - keys.Last());
 
        // Iterate the array arr
        // from K till the end
        for (int i = K; i < N; i++)
        {
 
            // Get the frequency of the
            // current element from the treemap
 
            if (!tm.ContainsKey(arr[i]))
            {
                tm[arr[i]] = 1;
            }
            else
            {
                // Increment the frequency
                // of the element
                tm[arr[i]] += 1;
            }
 
            int freq = tm[arr[i - K]];
 
            // If freq is 1 then remove the
            // value from the treemap
            if (freq == 1)
                tm.Remove(arr[i - K]);
 
            // Else reduce the frequency
            // of that element by 1
            else
                tm[arr[i - K]] = freq - 1;
 
            // Update maxDiff with the maximum
            // of difference between smallest
            // and greatest element in treemap
            // and maxDiff
            keys = tm.Keys.ToArray();
            Array.Sort(keys);
            maxDiff = Math.Max(maxDiff, Math.Abs(keys.First() - keys.Last()));
        }
 
        // Return the answer as maxDiff
        return maxDiff;
    }
 
    // Driver code
    public static void Main()
    {
 
        // Initialize the array
        int[] arr = { 2, 3, -1, -5, 4, 0 };
 
        // Initialize the value of K
        int K = 3;
 
        // Call the function and
        // print the result
        Console.Write(maxDiffK(arr, K));
    }
}
 
// This code is contributed by saurabh_jaiswal.


Javascript


输出
9

时间复杂度: O(N * log K)
辅助空间: O(N)