I remember, once I have been asked to replace elements in a sorted array to the sum of all elements which are greater or equal to that element.
Example
Input array A1 = {5, 12, 18, 22, 27}
Output Array should look be A1 = {84, 79, 67, 49, 27}
A[0] = 5+12+18+22+27 = 84
A[1] = 12+18+22+27 = 79
A[2] = 18+22+27 = 67
A[3] = 22+27 = 49
A[4] = 27
In a rush I figured out a way which takes two arrays and as follows.
public static int [] ReplaceArrayElementWithSum(int[] A1)
{
int sum = 0;
int[] A2 = new int[A1.Length];
for (int i = 0; i<A1.Length; i++)
{
sum = sum + A1[i];
}
A2[0] = sum;
for (int i = 0; i < A1.Length; i++)
{
if (i == 0)
{
A2[i] = sum;
}
else
{
A2[i] = A2[i - 1] - A1[i - 1];
}
}
return A2;
} Now let’s do the same thing in more efficient way.public static int[] ReplaceArrayElementWithSum2(int[] A1)
{
for (int i = A1.Length-2; i>=0; i--)
{
A1[i] = A1[i] + A1[i+1];
}
return A1;
} Please let me know if you can think of any other/better way.