Message on Whatsapp 8879355057 for DSA(OA + Interview) + Fullstack Dev Training + 1-1 Personalized Mentoring to get 10+LPA Job
0 like 0 dislike
1,907 views
in Online Assessments by Expert (110,460 points) | 1,907 views

1 Answer

0 like 0 dislike

For each element of an array, a counter is set to 0. The element is compared to each
element to its left. If the element to the left is greater, the absolute difference is subtracted
from the counter. If the element to the left is less, the absolute difference is added to the
counter. For each element of the array, determine the value of the counter. These values
should be stored in an array and returned.

 

e.g.
input
1,2,2,3
output
0,1,1,4

 

Looks like i*arr[i]-sum[i-1] ,i-1>=0;sum[i] is prefix sum till index i

 

//e.g.
//input 1 2 2 3
//output 0 1 1 4

 

vector arrayChallenge(vector arr)
{
vector ans;
ans.push_back(0);

 

for(int i = 0; i < arr.size(); i++)
{
int diff = arr[i]-arr[i-1];
int diffHandler = (i-1)*diff + diff + ans[i-1];
ans.push_back(diffHandler);
}
return ans;
}

by Expert (110,460 points)
0 0
For loop should start with i =1, rest logic is correct

Get best answers to any doubt/query/question related to programming , jobs, gate, internships and tech-companies. Feel free to ask a question and you will receive the best advice/suggestion related to anything you ask about software-engineering , development and programming problems .