生成数组,以便用它们的差异替换任何两个元素给出相同或更大的总和
给定一个非负整数N ,任务是生成一个数组,如果该数组的任何两个元素被它们的绝对差值替换,则当前数组的总和大于或大于生成的数组。
注意:如果有多个可能的数组,则返回其中任何一个
例子:
Input: N = 2
Output: arr[] = [1, 3]
Explanation: In the above example the sum of array is 4.
Select two indices 0 and 1 and replace 1 and 3 by |1-3| = 2, then array is [2, 2].
So now the sum is 4 which is equal to the previous sum.
Input: N = 3
Output: arr[] = [1, 10, 40]
Explanation: Firstly the total sum of array is 51.
Select two indices 0 and 1 and replace them with |arr[0] – arr[1]|.
Then the array would be arr = [9, 9, 40].
So now the total sum is 58 hence the sum is increased.
For another pair of indices 0 and 2
Replace arr[0] and arr[2] by |arr[0] – arr[2]|.
Then the array would be arr = [39, 10, 39].
So now the total sum is 88 hence the sum is increased.
For pair of indices 1 and 2
Replace arr[1] and arr[2] by |arr[1] – arr[2]|.
Then the array would be arr = [1, 30, 30].
So now the total sum is 61 hence the sum is increased.
So the above array is a possible answer answer
方法:这个问题可以根据以下数学观察来解决:
If there are two numbers a and b and we want to replace them by |a – b| such that the total sum remains same or increases then:
a + b ≤ |a – b| + |a – b|
=> a + b ≤ 2*|a – b|
Now consider a is the larger element, then
a + b ≤ 2*a – 2*b
=> b + 2*b ≤ 2*a – a
=> 3*b ≤ a
So the greater element must be at least 3 times of the smaller element.
基于上述观察可以看出,如果对于生成的数组(比如arr[] ),任何第 i 个元素的值至少为3*arr[i-1] ,那么该数组将满足给定条件。
按照下面提到的步骤来实现上述观察:
- 生成一个大小为 N 的数组arr[]并初始化arr[0] = 1 。
- 在数组中从i = 1 迭代到 N-1 :
- 将arr[i]设置为3*arr[i-1] 。
- 返回生成的数组。
下面是上述方法的实现。
C++
// C++ program for the above approach
#include
using namespace std;
#define ll long long int
// Function to generate the array
vector createArray(int N)
{
vector res;
// Initializing the arr[0] with 1
long long int ans = 1;
while (N--) {
res.push_back(ans);
// For every number we are multiplying
// the previous number with 3
ans *= 3;
}
return res;
}
// Driver code
int main()
{
int N = 3;
// Function call
vector ans = createArray(N);
for (int x : ans)
cout << x << " ";
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG {
// Function to generate the array
static Vector createArray(int N)
{
Vector res = new Vector();
// Initializing the arr[0] with 1
int ans = 1;
while (N != 0) {
res.add(ans);
// For every number we are multiplying
// the previous number with 3
ans *= 3;
N -= 1;
}
return res;
}
// Driver code
public static void main (String[] args) {
int N = 3;
// Function call
Vector ans = createArray(N);
ans.forEach((n) -> System.out.print(n));
}
}
// This code is contributed by hrithikgarg03188
1 3 9
时间复杂度: O(N)
辅助空间: O(N)