给定整数N ,任务是找到X和Y的不同对,以使X + Y = N且abs(X – Y)最小。
例子:
Input: N = 11
Output: 5 6
Explanation:
X = 5 and Y = 6 satisfy the given equation.
Therefore, the minimum absolute value of abs(X – Y) = 1.
Input: N = 12
Output: 5 7
天真的方法:解决此问题的最简单方法是生成X和Y的所有可能值,总和等于N,并打印X和Y的值,从而得出abs(X – Y)的最小绝对值。
时间复杂度: O(N 2 )
辅助空间: O(1)
高效的方法:可以基于以下观察来优化上述方法:
If N % 2 == 1, then pairs (N / 2) and (N / 2 + 1) have minimum absolute difference.
Otherwise, pairs (N / 2 – 1) and (N / 2 + 1) will have the minimum absolute difference.
请按照以下步骤解决问题:
- 检查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)