📌  相关文章
📜  从具有总和 K 的数组中计算最大可能对

📅  最后修改于: 2021-09-06 06:31:25             🧑  作者: Mango

给定一个由N 个整数和一个整数K组成的数组arr[] ,任务是从给定的数组中找到可能的总和为K的对的最大数量。

注意:每个数组元素都可以是一对的一部分。

例子:

双指针方法:这个想法是使用双指针技术。请按照以下步骤解决问题:

  • 将变量ans初始化为0以存储总和为K的最大对数。
  • 按升序对数组arr[]进行排序。
  • 将两个索引变量L初始化为0 ,将R初始化为(N – 1)以在已排序数组中查找候选元素。
  • 迭代直到L 小于 R并执行以下操作:
    • 检查arr[L]arr[R]的总和是否为 K。如果发现为真,则将ansL增加1并将R减少1
    • 如果arr[L]arr[R]的总和小于K ,则将L增加1
    • 否则,将R减少1
  • 经过以上步骤,打印ans的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count the maximum number
// of pairs from given array with sum K
void maxPairs(int nums[], int n, int k)
{
 
  // Sort array in increasing order
  sort(nums, nums + n);
 
  // Stores the final result
  int result = 0;
 
  // Initialize the left and right pointers
  int start = 0, end = n - 1;
 
  // Traverse array until start < end
  while (start < end) {
 
    if (nums[start] + nums[end] > k)
 
      // Decrement right by 1
      end--;
 
    else if (nums[start] + nums[end] < k)
 
      // Increment left by 1
      start++;
 
    // Increment result and left
    // pointer by 1 and decrement
    // right pointer by 1
    else
    {
      start++;
      end--;
      result++;
    }
  }
 
  // Print the result
  cout << result << endl;;
}
 
// Driver Code
int main()
{
  int arr[] = { 1, 2, 3, 4 };
  int n = sizeof(arr)/sizeof(arr[0]);
  int K = 5;
 
  // Function Call
  maxPairs(arr, n, K);
 
  return 0;
}
 
// This code is contributed by AnkThon


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to count the maximum number
    // of pairs from given array with sum K
    public static void maxPairs(int[] nums, int k)
    {
        // Sort array in increasing order
        Arrays.sort(nums);
 
        // Stores the final result
        int result = 0;
 
        // Initialize the left and right pointers
        int start = 0, end = nums.length - 1;
 
        // Traverse array until start < end
        while (start < end) {
 
            if (nums[start] + nums[end] > k)
 
                // Decrement right by 1
                end--;
 
            else if (nums[start] + nums[end] < k)
 
                // Increment left by 1
                start++;
 
            // Increment result and left
            // pointer by 1 and decrement
            // right pointer by 1
            else {
                start++;
                end--;
                result++;
            }
        }
 
        // Print the result
        System.out.println(result);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 4 };
        int K = 5;
 
        // Function Call
        maxPairs(arr, K);
    }
}


Python3
# Python3 program for the above approach
 
# Function to count the maximum number
# of pairs from given array with sum K
def maxPairs(nums, k):
     
    # Sort array in increasing order
    nums = sorted(nums)
 
    # Stores the final result
    result = 0
 
    # Initialize the left and right pointers
    start, end = 0, len(nums) - 1
     
    # Traverse array until start < end
    while (start < end):
        if (nums[start] + nums[end] > k):
 
            # Decrement right by 1
            end -= 1
 
        elif (nums[start] + nums[end] < k):
 
            # Increment left by 1
            start += 1
             
        # Increment result and left
        # pointer by 1 and decrement
        # right pointer by 1
        else:
            start += 1
            end -= 1
            result += 1
 
    # Print the result
    print(result)
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 1, 2, 3, 4 ]
    K = 5
 
    # Function Call
    maxPairs(arr, K)
     
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
  
class GFG{
      
    // Function to count the maximum number
    // of pairs from given array with sum K
    public static void maxPairs(int[] nums, int k)
    {
       
        // Sort array in increasing order
        Array.Sort(nums);
  
        // Stores the final result
        int result = 0;
  
        // Initialize the left and right pointers
        int start = 0, end = nums.Length - 1;
  
        // Traverse array until start < end
        while (start < end) {
  
            if (nums[start] + nums[end] > k)
  
                // Decrement right by 1
                end--;
  
            else if (nums[start] + nums[end] < k)
  
                // Increment left by 1
                start++;
  
            // Increment result and left
            // pointer by 1 and decrement
            // right pointer by 1
            else
            {
                start++;
                end--;
                result++;
            }
        }
  
        // Print the result
        Console.Write(result);
    }
  
// Driver Code   
public static void Main()
{
  int[] arr = { 1, 2, 3, 4 };
  int K = 5;
   
  // Function Call
  maxPairs(arr, K);
}
}
 
// This code is contributed by susmitakundugoaldanga


Javascript


C++
// C++ program for the above approach
#include 
#include 
using namespace std;
 
// Function to find the maximum number
// of pairs with a sum K such that
// same element can't be used twice
void maxPairs(vector nums, int k)
{
     
    // Initialize a hashm
    map m;
     
    // Store the final result
    int result = 0;
 
    // Iterate over the array nums[]
    for(auto i : nums)
    {
         
        // Decrement its frequency
        // in m and increment
        // the result by 1
        if (m.find(i) != m.end() && m[i] > 0)
        {
            m[i] = m[i] - 1;
            result++;
        }
 
        // Increment its frequency by 1
        // if it is already present in m.
        // Otherwise, set its frequency to 1
        else
        {
            m[k - i] = m[k - i] + 1;
        }
    }
     
    // Print the result
    cout << result;
}
 
// Driver Code
int main()
{
    vector arr = { 1, 2, 3, 4 };
    int K = 5;
 
    // Function Call
    maxPairs(arr, K);
}
 
// This code is contributed by grand_master


Java
// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to find the maximum number
    // of pairs with a sum K such that
    // same element can't be used twice
    public static void maxPairs(
        int[] nums, int k)
    {
 
        // Initialize a hashmap
        Map map
            = new HashMap<>();
 
        // Store the final result
        int result = 0;
 
        // Iterate over the array nums[]
        for (int i : nums) {
 
            // Decrement its frequency
            // in map and increment
            // the result by 1
            if (map.containsKey(i) &&
                map.get(i) > 0)
            {
 
                map.put(i, map.get(i) - 1);
                result++;
            }
 
            // Increment its frequency by 1
            // if it is already present in map.
            // Otherwise, set its frequency to 1
            else
            {
                map.put(k - i,
                        map.getOrDefault(k - i, 0) + 1);
            }
        }
 
        // Print the result
        System.out.println(result);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 4 };
        int K = 5;
 
        // Function Call
        maxPairs(arr, K);
    }
}


Python3
# Python3 program for the above approach
 
# Function to find the maximum number
# of pairs with a sum K such that
# same element can't be used twice
def maxPairs(nums, k) :
     
    # Initialize a hashm
    m = {}
     
    # Store the final result
    result = 0
 
    # Iterate over the array nums[]
    for i in nums :
         
        # Decrement its frequency
        # in m and increment
        # the result by 1
        if ((i in m) and m[i] > 0) :       
            m[i] = m[i] - 1
            result += 1
 
        # Increment its frequency by 1
        # if it is already present in m.
        # Otherwise, set its frequency to 1
        else :
         
            if k - i in m :
                m[k - i] += 1
            else :
                m[k - i] = 1
     
    # Print the result
    print(result)
 
# Driver code   
arr = [ 1, 2, 3, 4 ]
K = 5
 
# Function Call
maxPairs(arr, K)
 
# This code is contributed by divyesh072019


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
    // Function to find the maximum number
    // of pairs with a sum K such that
    // same element can't be used twice
    public static void maxPairs(
        int[] nums, int k)
    {
 
        // Initialize a hashmap
        Dictionary map
            = new Dictionary();
 
        // Store the readonly result
        int result = 0;
 
        // Iterate over the array nums[]
        foreach (int i in nums)
        {
 
            // Decrement its frequency
            // in map and increment
            // the result by 1
            if (map.ContainsKey(i) &&
                map[i] > 0)
            {
 
                map[i] = map[i] - 1;
                result++;
            }
 
            // Increment its frequency by 1
            // if it is already present in map.
            // Otherwise, set its frequency to 1
            else
            {
              if (!map.ContainsKey(k - i))
                  map.Add(k - i, 1);
              else
                  map[i] = map[i] + 1;
            }
        }
 
        // Print the result
        Console.WriteLine(result);
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] arr = {1, 2, 3, 4};
        int K = 5;
 
        // Function Call
        maxPairs(arr, K);
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:

2

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

高效的方法:为了优化上述方法,想法是使用散列。请按照以下步骤解决问题:

  • 初始化一个变量,比如ans ,以存储总和为K的最大对数。
  • 初始化一个哈希表,比如S ,以存储arr[]中元素的频率。
  • 使用变量遍历数组arr[] ,例如i ,并执行以下步骤:
    • 如果(K – arr[i])的频率为正,则将ans增加1并将(K – arr[i])的频率减少1
    • 否则,在哈希表中插入频率为1 的arr[i]
  • 完成以上步骤后,打印ans的值作为结果。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
#include 
using namespace std;
 
// Function to find the maximum number
// of pairs with a sum K such that
// same element can't be used twice
void maxPairs(vector nums, int k)
{
     
    // Initialize a hashm
    map m;
     
    // Store the final result
    int result = 0;
 
    // Iterate over the array nums[]
    for(auto i : nums)
    {
         
        // Decrement its frequency
        // in m and increment
        // the result by 1
        if (m.find(i) != m.end() && m[i] > 0)
        {
            m[i] = m[i] - 1;
            result++;
        }
 
        // Increment its frequency by 1
        // if it is already present in m.
        // Otherwise, set its frequency to 1
        else
        {
            m[k - i] = m[k - i] + 1;
        }
    }
     
    // Print the result
    cout << result;
}
 
// Driver Code
int main()
{
    vector arr = { 1, 2, 3, 4 };
    int K = 5;
 
    // Function Call
    maxPairs(arr, K);
}
 
// This code is contributed by grand_master

Java

// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to find the maximum number
    // of pairs with a sum K such that
    // same element can't be used twice
    public static void maxPairs(
        int[] nums, int k)
    {
 
        // Initialize a hashmap
        Map map
            = new HashMap<>();
 
        // Store the final result
        int result = 0;
 
        // Iterate over the array nums[]
        for (int i : nums) {
 
            // Decrement its frequency
            // in map and increment
            // the result by 1
            if (map.containsKey(i) &&
                map.get(i) > 0)
            {
 
                map.put(i, map.get(i) - 1);
                result++;
            }
 
            // Increment its frequency by 1
            // if it is already present in map.
            // Otherwise, set its frequency to 1
            else
            {
                map.put(k - i,
                        map.getOrDefault(k - i, 0) + 1);
            }
        }
 
        // Print the result
        System.out.println(result);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 1, 2, 3, 4 };
        int K = 5;
 
        // Function Call
        maxPairs(arr, K);
    }
}

蟒蛇3

# Python3 program for the above approach
 
# Function to find the maximum number
# of pairs with a sum K such that
# same element can't be used twice
def maxPairs(nums, k) :
     
    # Initialize a hashm
    m = {}
     
    # Store the final result
    result = 0
 
    # Iterate over the array nums[]
    for i in nums :
         
        # Decrement its frequency
        # in m and increment
        # the result by 1
        if ((i in m) and m[i] > 0) :       
            m[i] = m[i] - 1
            result += 1
 
        # Increment its frequency by 1
        # if it is already present in m.
        # Otherwise, set its frequency to 1
        else :
         
            if k - i in m :
                m[k - i] += 1
            else :
                m[k - i] = 1
     
    # Print the result
    print(result)
 
# Driver code   
arr = [ 1, 2, 3, 4 ]
K = 5
 
# Function Call
maxPairs(arr, K)
 
# This code is contributed by divyesh072019

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
    // Function to find the maximum number
    // of pairs with a sum K such that
    // same element can't be used twice
    public static void maxPairs(
        int[] nums, int k)
    {
 
        // Initialize a hashmap
        Dictionary map
            = new Dictionary();
 
        // Store the readonly result
        int result = 0;
 
        // Iterate over the array nums[]
        foreach (int i in nums)
        {
 
            // Decrement its frequency
            // in map and increment
            // the result by 1
            if (map.ContainsKey(i) &&
                map[i] > 0)
            {
 
                map[i] = map[i] - 1;
                result++;
            }
 
            // Increment its frequency by 1
            // if it is already present in map.
            // Otherwise, set its frequency to 1
            else
            {
              if (!map.ContainsKey(k - i))
                  map.Add(k - i, 1);
              else
                  map[i] = map[i] + 1;
            }
        }
 
        // Print the result
        Console.WriteLine(result);
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] arr = {1, 2, 3, 4};
        int K = 5;
 
        // Function Call
        maxPairs(arr, K);
    }
}
 
// This code is contributed by 29AjayKumar

Javascript


输出:
2

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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live