📌  相关文章
📜  与数组相距至少 K 距离的对的最小总和

📅  最后修改于: 2021-10-26 06:53:41             🧑  作者: Mango

给定一个大小为N的整数数组A[] ,任务是找到任何一对至少相距K 个索引的数组元素可以获得的最小和。

例子:

天真的方法:
解决该问题的最简单方法是为每个i索引迭代索引[i + K, N – 1]并找到最小元素,例如min 。检查min + A[i]是否小于目前获得的最小总和并相应地更新minimum_sum 。最后,打印minimum_sum

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include
using namespace std;
 
// Function to find the minimum
// sum of two elements that
// are atleast K distance apart
void findMinSum(int A[], int K, int n)
{
    int minimum_sum = INT_MAX;
 
    // Iterate over the array
    for(int i = 0; i < n; i++)
    {
         
        // Initialize the min value
        int mini = INT_MAX;
 
        // Iterate from i + k to N
        for(int j = i + K; j < n; j++)
 
            // Find the minimum
            mini = min(mini, A[j]);
 
        if (mini == INT_MAX)
            continue;
 
        // Update the minimum sum
        minimum_sum = min(minimum_sum,
                          A[i] + mini);
    }
 
    // Print the answer
    cout << (minimum_sum);
}
 
// Driver Code
int main()
{
    int A[] = { 4, 2, 5, 4, 3, 2, 5 };
    int K = 3;
    int n = sizeof(A) / sizeof(A[0]);
 
    findMinSum(A, K, n);
    return 0;
}
 
// This code is contributed by chitranayal


Java
// Java Program to implement
// the above approach
 
import java.util.*;
class GFG {
 
    // Function to find the minimum
    // sum of two elements that
    // are atleast K distance apart
    public static void
    findMinSum(int A[], int K)
    {
        // Length of the array
        int n = A.length;
 
        int minimum_sum
            = Integer.MAX_VALUE;
 
        // Iterate over the array
        for (int i = 0; i < n; i++) {
 
            // Initialize the min value
            int min = Integer.MAX_VALUE;
 
            // Iterate from i + k to N
            for (int j = i + K; j < n; j++)
 
                // Find the minimum
                min = Math.min(min, A[j]);
 
            if (min == Integer.MAX_VALUE)
                continue;
 
            // Update the minimum sum
            minimum_sum = Math.min(minimum_sum,
                                   A[i] + min);
        }
 
        // Print the answer
        System.out.println(minimum_sum);
    }
 
    // Driver Code
    public static void
        main(String[] args)
    {
 
        int A[] = { 4, 2, 5, 4, 3, 2, 5 };
        int K = 3;
 
        findMinSum(A, K);
    }
}


Python3
# Python3 Program to implement
# the above approach
import sys
 
# Function to find the minimum
# sum of two elements that
# are atleast K distance apart
def findMinSum(A, K):
   
    # Length of the array
    n = len(A);
 
    minimum_sum = sys.maxsize;
 
    # Iterate over the array
    for i in range(n):
 
        # Initialize the min value
        minimum = sys.maxsize;
 
        # Iterate from i + k to N
        for j in range(i + K, n, 1):
 
            # Find the minimum
            minimum = min(minimum, A[j]);
 
        if (minimum == sys.maxsize):
            continue;
 
        # Update the minimum sum
        minimum_sum = min(minimum_sum, A[i] + minimum);
 
    # Prthe answer
    print(minimum_sum);
 
# Driver Code
if __name__ == '__main__':
    A = [4, 2, 5, 4, 3, 2, 5];
    K = 3;
 
    findMinSum(A, K);
 
# This code is contributed by sapnasingh4991


C#
// C# Program to implement
// the above approach
using System;
class GFG{
 
  // Function to find the minimum
  // sum of two elements that
  // are atleast K distance apart
  public static void findMinSum(int []A,
                                int K)
  {
    // Length of the array
    int n = A.Length;
 
    int minimum_sum = int.MaxValue;
 
    // Iterate over the array
    for (int i = 0; i < n; i++)
    {
 
      // Initialize the min value
      int min = int.MaxValue;
 
      // Iterate from i + k to N
      for (int j = i + K; j < n; j++)
 
        // Find the minimum
        min = Math.Min(min, A[j]);
 
      if (min == int.MaxValue)
        continue;
 
      // Update the minimum sum
      minimum_sum = Math.Min(minimum_sum,
                             A[i] + min);
    }
 
    // Print the answer
    Console.WriteLine(minimum_sum);
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int []A = { 4, 2, 5, 4, 3, 2, 5 };
    int K = 3;
 
    findMinSum(A, K);
  }
}
 
// This code is contributed by Rohit_ranjan


Javascript


C++
// C++ Program to implement
//the above approach
#include 
using namespace std;
 
// Function to find the minimum
// sum of two elements that
// are atleast K distance apart
void findMinSum(int A[], int K, int len)
{
 
  // Length of the array
  int n = len;
  int suffix_min[n] = {0};
 
  suffix_min[n - 1] = A[n - 1];
 
  // Find the suffix array
  for (int i = n - 2; i >= 0; i--)
    suffix_min[i] = min(suffix_min[i + 1], A[i]);
 
  int min_sum = INT_MAX;
 
  // Iterate in the array
  for (int i = 0; i < n; i++)
  {
    if (i + K < n)
 
      // Update minimum sum
      min_sum = min(min_sum, A[i] +
                    suffix_min[i + K]);
  }
 
  // Print the answer
  cout << min_sum;
}
 
 
// Driver Code
int main()
{
    int A[] = { 1, 2, 3, 4, 5, 6 };
    int K = 2;
    int n = sizeof(A) / sizeof(A[0]);
    findMinSum(A, K, n);
    return 0;
}
 
// This code is contributed by Rohit_ranjan


Java
// Java Program to implement
// the above approach
 
import java.util.*;
class GFG {
 
    // Function to find the minimum
    // sum of two elements that
    // are atleast K distance apart
    public static void
    findMinSum(int A[], int K)
    {
 
        // Length of the array
        int n = A.length;
        int suffix_min[] = new int[n];
 
        suffix_min[n - 1] = A[n - 1];
 
        // Find the suffix array
        for (int i = n - 2; i >= 0; i--)
            suffix_min[i]
                = Math.min(suffix_min[i + 1],
                           A[i]);
 
        int min_sum = Integer.MAX_VALUE;
 
        // Iterate in the array
        for (int i = 0; i < n; i++) {
 
            if (i + K < n)
 
                // Update minimum sum
                min_sum = Math.min(
                    min_sum, A[i]
                                 + suffix_min[i + K]);
        }
 
        // Print the answer
        System.out.println(min_sum);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int A[] = { 1, 2, 3, 4, 5, 6 };
        int K = 2;
 
        findMinSum(A, K);
    }
}


Python3
# Python3 program to implement
# the above approach
import sys
 
# Function to find the minimum
# sum of two elements that
# are atleast K distance apart
def findMinSum(A, K):
     
    # Length of the array
    n = len(A);
     
    suffix_min = [0] * n;
    suffix_min[n - 1] = A[n - 1];
 
    # Find the suffix array
    for i in range(n - 2, -1, -1):
        suffix_min[i] = min(suffix_min[i + 1], A[i]);
 
    min_sum = sys.maxsize;
 
    # Iterate in the array
    for i in range(n):
        if (i + K < n):
 
            # Update minimum sum
            min_sum = min(min_sum, A[i] +
                          suffix_min[i + K]);
 
    # Print the answer
    print(min_sum);
 
# Driver Code
if __name__ == '__main__':
     
    A = [ 1, 2, 3, 4, 5, 6 ];
    K = 2;
 
    findMinSum(A, K);
 
# This code is contributed by Amit Katiyar


C#
// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to find the minimum
// sum of two elements that
// are atleast K distance apart
public static void findMinSum(int []A, int K)
{
     
    // Length of the array
    int n = A.Length;
    int []suffix_min = new int[n];
 
    suffix_min[n - 1] = A[n - 1];
 
    // Find the suffix array
    for(int i = n - 2; i >= 0; i--)
        suffix_min[i] = Math.Min(suffix_min[i + 1],
                                          A[i]);
 
    int min_sum = int.MaxValue;
 
    // Iterate in the array
    for(int i = 0; i < n; i++)
    {
        if (i + K < n)
 
            // Update minimum sum
            min_sum = Math.Min(min_sum, A[i] +
                               suffix_min[i + K]);
    }
 
    // Print the answer
    Console.WriteLine(min_sum);
}
 
// Driver Code
public static void Main(String[] args)
{
    int []A = { 1, 2, 3, 4, 5, 6 };
    int K = 2;
 
    findMinSum(A, K);
}
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
4

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

有效的方法:
可以使用Suffix Array优化上述方法。请按照以下步骤操作:

  • 初始化一个后缀数组(比如suffix[] ),其中suffix[i]存储从索引N-1 到 i的所有元素的最小值。
  • 对于任何i索引,相距K距离的最小元素存储在后缀数组中的索引i + K 处
  • 对于i范围从0 到 N – 1 ,检查是否A[i] + suffix[i + k] < minimum_sum并相应地更新minimum_sum
  • 最后,打印minimum_sum作为所需答案。

下面是上述方法的实现:

C++

// C++ Program to implement
//the above approach
#include 
using namespace std;
 
// Function to find the minimum
// sum of two elements that
// are atleast K distance apart
void findMinSum(int A[], int K, int len)
{
 
  // Length of the array
  int n = len;
  int suffix_min[n] = {0};
 
  suffix_min[n - 1] = A[n - 1];
 
  // Find the suffix array
  for (int i = n - 2; i >= 0; i--)
    suffix_min[i] = min(suffix_min[i + 1], A[i]);
 
  int min_sum = INT_MAX;
 
  // Iterate in the array
  for (int i = 0; i < n; i++)
  {
    if (i + K < n)
 
      // Update minimum sum
      min_sum = min(min_sum, A[i] +
                    suffix_min[i + K]);
  }
 
  // Print the answer
  cout << min_sum;
}
 
 
// Driver Code
int main()
{
    int A[] = { 1, 2, 3, 4, 5, 6 };
    int K = 2;
    int n = sizeof(A) / sizeof(A[0]);
    findMinSum(A, K, n);
    return 0;
}
 
// This code is contributed by Rohit_ranjan

Java

// Java Program to implement
// the above approach
 
import java.util.*;
class GFG {
 
    // Function to find the minimum
    // sum of two elements that
    // are atleast K distance apart
    public static void
    findMinSum(int A[], int K)
    {
 
        // Length of the array
        int n = A.length;
        int suffix_min[] = new int[n];
 
        suffix_min[n - 1] = A[n - 1];
 
        // Find the suffix array
        for (int i = n - 2; i >= 0; i--)
            suffix_min[i]
                = Math.min(suffix_min[i + 1],
                           A[i]);
 
        int min_sum = Integer.MAX_VALUE;
 
        // Iterate in the array
        for (int i = 0; i < n; i++) {
 
            if (i + K < n)
 
                // Update minimum sum
                min_sum = Math.min(
                    min_sum, A[i]
                                 + suffix_min[i + K]);
        }
 
        // Print the answer
        System.out.println(min_sum);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int A[] = { 1, 2, 3, 4, 5, 6 };
        int K = 2;
 
        findMinSum(A, K);
    }
}

蟒蛇3

# Python3 program to implement
# the above approach
import sys
 
# Function to find the minimum
# sum of two elements that
# are atleast K distance apart
def findMinSum(A, K):
     
    # Length of the array
    n = len(A);
     
    suffix_min = [0] * n;
    suffix_min[n - 1] = A[n - 1];
 
    # Find the suffix array
    for i in range(n - 2, -1, -1):
        suffix_min[i] = min(suffix_min[i + 1], A[i]);
 
    min_sum = sys.maxsize;
 
    # Iterate in the array
    for i in range(n):
        if (i + K < n):
 
            # Update minimum sum
            min_sum = min(min_sum, A[i] +
                          suffix_min[i + K]);
 
    # Print the answer
    print(min_sum);
 
# Driver Code
if __name__ == '__main__':
     
    A = [ 1, 2, 3, 4, 5, 6 ];
    K = 2;
 
    findMinSum(A, K);
 
# This code is contributed by Amit Katiyar

C#

// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to find the minimum
// sum of two elements that
// are atleast K distance apart
public static void findMinSum(int []A, int K)
{
     
    // Length of the array
    int n = A.Length;
    int []suffix_min = new int[n];
 
    suffix_min[n - 1] = A[n - 1];
 
    // Find the suffix array
    for(int i = n - 2; i >= 0; i--)
        suffix_min[i] = Math.Min(suffix_min[i + 1],
                                          A[i]);
 
    int min_sum = int.MaxValue;
 
    // Iterate in the array
    for(int i = 0; i < n; i++)
    {
        if (i + K < n)
 
            // Update minimum sum
            min_sum = Math.Min(min_sum, A[i] +
                               suffix_min[i + K]);
    }
 
    // Print the answer
    Console.WriteLine(min_sum);
}
 
// Driver Code
public static void Main(String[] args)
{
    int []A = { 1, 2, 3, 4, 5, 6 };
    int K = 2;
 
    findMinSum(A, K);
}
}
 
// This code is contributed by 29AjayKumar

Javascript


输出:
4

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

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程