📜  找到总和 N 具有最小绝对差的对

📅  最后修改于: 2021-10-26 07:00:47             🧑  作者: Mango

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

例子:

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

时间复杂度: 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)