-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindClosestSumPair.cs
More file actions
83 lines (74 loc) · 2.51 KB
/
FindClosestSumPair.cs
File metadata and controls
83 lines (74 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System;
using System.Collections.Generic;
namespace DA.Algorithms.Problems
{
public static class FindClosestSumPair
{
/// <summary>
/// Find a pair in array whose sum is closest to given value
/// <para>Time Complexity - O(n^2)</para>
/// </summary>
///
/// <param name="array">Collection with positive integers</param>
/// <param name="value">Target value</param>
///
/// <returns>
/// Return a collection with two numbers that can give closest sum to the value
/// </returns>
public static int[] ClosestPair (int[] array, int value)
{
int difference = int.MaxValue;
int first = -1;
int second = -1;
int current;
for (int i = 0; i < array.Length; i++)
{
for (int j = 0; j < array.Length; j++)
{
current = Math.Abs (value - (array[i] + array[j]));
if (current < difference)
{
difference = current;
first = array[i];
second = array[j];
}
}
}
return new int[] { first, second };
}
/// <summary>
/// Find a pair in array whose sum is closest to given value
/// <para>Time Complexity - O(n.logn)</para>
/// </summary>
///
/// <param name="array">Collection with positive integers</param>
/// <param name="value">Target value</param>
///
/// <returns>
/// Return a collection with two numbers that can give closest sum to the value
/// </returns>
public static void ClosestPairUsingSorting (int[] array, int value)
{
int first = 0;
int second = 0;
int start = 0;
int stop = array.Length - 1;
Array.Sort (array);
int difference = int.MaxValue;
int current = 0;
while (start < stop)
{
current = (value - (array[start] + array[stop]));
if (Math.Abs (current) < difference)
{
difference = Math.Abs (current);
first = array[start];
second = array[stop];
}
if (current == 0) break;
else if (current > 0) ++start;
else --stop;
}
}
}
}