Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
[ad_1]
Given an array arr[] of measurement N and three integers X, Y and Ok, the duty is to depend the variety of pairs (i, j) the place i < j such that (arr[i] * X + arr[j] * Y) = Ok.
Examples:
Enter: arr[] = {3, 1, 2, 3}, X = 4, Y = 2, Ok = 14
Output: 2
Rationalization: The doable pairs are: (1, 2), (3, 4).
For i = 1, j = 2, Worth of the expression = 4 * 3 + 2 * 1 = 14.
For i = 3, j = 4, Worth of the expression = 4 * 2 + 2 * 3 = 14.Enter: arr[] = [1, 3, 2], X = 1, Y = 3, Ok = 7
Output: 2
Rationalization: The doable pairs are: (1, 2), (2, 3).
For i = 1, j = 2, Worth of the expression = 1 * 1 + 2 * 3 = 7.
For i = 2, j = 3, Worth of the expression = 1 * 3 + 2 * 2 = 7.Enter: N = 2, arr[] = [1, 2], X =1, Y = 1, goal = 2
Output: 0
Rationalization: No pair fulfill the above situation.
For i = 1, j = 2, Worth of the expression = 1 * 1 + 1 * 2 = 3.
Naive Method: The fundamental thought to unravel the issue is as follows:
Discover all doable pairs of (i, j) and for every pair verify if (arr[i]*X + arr[j]*Y = Ok). In that case then increment the depend of pairs.
Comply with the beneath steps to implement the thought:
Beneath is the implementation of the above strategy.
|
Time Complexity: O(N2)
Area Complexity: O(1)
Environment friendly Method: The issue might be solved effectively based mostly on the next mathematical remark:
arr[i]*X + arr[j]*Y = Ok
arr[i]*X = Ok – arr[j]*Y
So (Ok – arr[j]*Y) should be divisible by X and if arr[j] is discovered then the worth of arr[i] should be (Ok – arr[j]*Y)/X.So to unravel the issue based mostly on the above remark, take into account every worth as arr[j] and attempt to discover the presence of arr[i] utilizing the above relation the place i is lower than j.
The above remark might be applied utilizing frequency counting. Comply with the beneath steps to unravel this drawback :
Beneath is the implementation of the above strategy :
|
Time Complexity: O(N)
Auxiliary Area: O(N)
[ad_2]