📌  相关文章
📜  找出一对总和N且绝对差最小的对

📅  最后修改于: 2021-04-29 05:29:46             🧑  作者: Mango

给定整数N ,任务是找到XY的不同对,以使X + Y = N且abs(X – Y)最小。

例子:

天真的方法:解决此问题的最简单方法是生成XY的所有可能值,总和等于N,并打印XY的值,从而得出abs(X – Y)的最小绝对值。

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

高效的方法:可以基于以下观察来优化上述方法:

请按照以下步骤解决问题:

  • 检查N是否为奇数。如果发现是正确的,则打印(N / 2)(N / 2 +1)的下限值作为所需答案。
  • 否则,打印(N / 2 – 1)(N / 2 + 1)的值

下面是上述方法的实现:

C++
// C++ program to implement
// the above approach
#include 
using namespace std;
 
// Function to find the value of X and Y
// having minimum value of abs(X - Y)
void findXandYwithminABSX_Y(int N)
{
    // If N is an odd number
    if (N % 2 == 1) {
        cout << (N / 2) << " " << (N / 2 + 1);
    }
 
    // If N is an even number
    else {
        cout << (N / 2 - 1) << " " << (N / 2 + 1);
    }
}
 
// Driver Code
int main()
{
    int N = 12;
    findXandYwithminABSX_Y(N);
}


Java
// Java program to implement
// the above approach
import java.util.*;
class GFG {
 
    // Function to find the value
    // of X and Y having minimum
    // value of Math.abs(X - Y)
    static void findXandYwithminABSX_Y(int N)
    {
        // If N is an odd number
        if (N % 2 == 1) {
            System.out.print((N / 2) + " " + (N / 2 + 1));
        }
 
        // If N is an even number
        else {
            System.out.print((N / 2 - 1) + " "
                             + (N / 2 + 1));
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 12;
        findXandYwithminABSX_Y(N);
    }
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 program to implement
# the above approach
 
# Function to find the value of X and Y
# having minimum value of abs(X - Y)
 
 
def findXandYwithminABSX_Y(N):
 
    # If N is an odd number
    if (N % 2 == 1):
        print((N // 2), (N // 2 + 1))
 
    # If N is an even number
    else:
        print((N // 2 - 1), (N // 2 + 1))
 
 
# Driver Code
if __name__ == '__main__':
 
    N = 12
 
    findXandYwithminABSX_Y(N)
 
# This code is contributed by mohit kumar 29


C#
// C# program to implement
// the above approach
using System;
class GFG {
 
    // Function to find the value
    // of X and Y having minimum
    // value of Math.abs(X - Y)
    static void findXandYwithminABSX_Y(int N)
    {
        // If N is an odd number
        if (N % 2 == 1) {
            Console.Write((N / 2) + " " + (N / 2 + 1));
        }
 
        // If N is an even number
        else {
            Console.Write((N / 2 - 1) + " " + (N / 2 + 1));
        }
    }
 
    // Driver Code
    public static void Main()
    {
        int N = 12;
        findXandYwithminABSX_Y(N);
    }
}
 
// This code is contributed by bgangwar59


PHP


Javascript


输出:
5 7

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