Children candies Hackerrank challenge : optimising the solutionHow to get the children of the $(this) selector?wrong answer in children trips in codechef october challenge?Unable to understand algorithmWhy is my Dijkstra code failing?Debugging hackerrank week of code Lazy SortingHackerRank Candies distributionGridland Metro Hackerrank Javawhat is wrong with this DP solution?Shortest Reach Graph on HackerRankPython program Terminated due to timeout - HackerRank
How does The Fools Guild make its money?
Why are physicists so interested in irreps if in their non-block-diagonal form they mix all components of a vector?
Can a PC attack themselves with an unarmed strike?
Write an interpreter for *
Blocking people from taking pictures of me with smartphone
Why does Intel's Haswell chip allow multiplication to be twice as fast as addition?
Is multiplication of real numbers uniquely defined as being distributive over addition?
How do I calculate the difference in lens reach between a superzoom compact and a DSLR zoom lens?
Is there a loss of quality when converting RGB to HEX?
What is the best way to cause swarm intelligence to be destroyed?
Reusing story title as chapter title
Is this cheap "air conditioner" able to cool a room?
What method to use in a batch apex in order to get authentication token from a remote server?
Shabbat clothing on shabbat chazon
Why is there a need to prevent a racist, sexist, or otherwise bigoted vendor from discriminating who they sell to?
SQL Minimum Row count
Was the 2019 Lion King film made through motion capture?
Improve survivability of bicycle container
How to help new students accept function notation
Can an SPI slave start a transmission in full-duplex mode?
Why did the RAAF procure the F/A-18 despite being purpose-built for carriers?
English - Acceptable use of parentheses in an author's name
Can a character who casts Shapechange and turns into a spellcaster use innate spellcasting to cast spells with a long casting time?
How can I tell if a flight itinerary is fake?
Children candies Hackerrank challenge : optimising the solution
How to get the children of the $(this) selector?wrong answer in children trips in codechef october challenge?Unable to understand algorithmWhy is my Dijkstra code failing?Debugging hackerrank week of code Lazy SortingHackerRank Candies distributionGridland Metro Hackerrank Javawhat is wrong with this DP solution?Shortest Reach Graph on HackerRankPython program Terminated due to timeout - HackerRank
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I am trying to solve an hackerrank challenge in JavaScript, and although for most of the test instances my solution performs quite well, I keep getting a timeout for some of them (Hackerrank has it set for 10 seconds for JavaScript challenges). The problem is described below:
There are N children standing in a line. Initially the i-th child has a[i]
candies. Some of the children have more candies than others. You have
to make sure that every student has the same number of candies. In one
operation you can tell one of the children to give a single candy to
the left neighbour, or to the right one. How many operations do you
need to make sure every student has same number of candies? Print the
minimal possible number of operations. The input is a multiline
string, where the first line contains a single integer N, and the next
line contains N space separated integers.
I solved this problem by calculating which number of candies should be given to each and every kid, and then iterate the array containing the number of candies, either grabbing candies from the rightmost positions (in case the child wouldn't have enough), or passing candies to the right position (in case the child would have more than needed)
This is the code I used for the challenge:
function processData(input) /),
n = tmp[0]
tmp.shift() // remove first element from tmp (the N variable)
let s=0, a = tmp.map(function(ai) novo=parseInt(ai, 10);s+=novo;return(novo)),
obj = s/n, ops = 0
for(var i=0; i<n; i++)
if(a[i] > obj)
let moved = a[i]-obj
a[i]-=moved
a[i+1]+=moved
ops+=moved
else
for(var j=i+1; a[i] != obj; j++)
if(a[j]===0)
ops++
else
let moved = Math.min(a[j], obj-a[i])
a[i]+=moved
a[j]-=moved
ops+=moved
//console.log(a)
console.log(ops)
Any idea on what is the problem?
How would you optimise my code?
Link to the challenge : https://www.hackerrank.com/contests/coc1/challenges/candies-1
EDIT
After some optimisations, my solution now fails 3 of the test cases (the same ones it was failing before due to timeout). It was not a performance issue
javascript algorithm optimization
add a comment |
I am trying to solve an hackerrank challenge in JavaScript, and although for most of the test instances my solution performs quite well, I keep getting a timeout for some of them (Hackerrank has it set for 10 seconds for JavaScript challenges). The problem is described below:
There are N children standing in a line. Initially the i-th child has a[i]
candies. Some of the children have more candies than others. You have
to make sure that every student has the same number of candies. In one
operation you can tell one of the children to give a single candy to
the left neighbour, or to the right one. How many operations do you
need to make sure every student has same number of candies? Print the
minimal possible number of operations. The input is a multiline
string, where the first line contains a single integer N, and the next
line contains N space separated integers.
I solved this problem by calculating which number of candies should be given to each and every kid, and then iterate the array containing the number of candies, either grabbing candies from the rightmost positions (in case the child wouldn't have enough), or passing candies to the right position (in case the child would have more than needed)
This is the code I used for the challenge:
function processData(input) /),
n = tmp[0]
tmp.shift() // remove first element from tmp (the N variable)
let s=0, a = tmp.map(function(ai) novo=parseInt(ai, 10);s+=novo;return(novo)),
obj = s/n, ops = 0
for(var i=0; i<n; i++)
if(a[i] > obj)
let moved = a[i]-obj
a[i]-=moved
a[i+1]+=moved
ops+=moved
else
for(var j=i+1; a[i] != obj; j++)
if(a[j]===0)
ops++
else
let moved = Math.min(a[j], obj-a[i])
a[i]+=moved
a[j]-=moved
ops+=moved
//console.log(a)
console.log(ops)
Any idea on what is the problem?
How would you optimise my code?
Link to the challenge : https://www.hackerrank.com/contests/coc1/challenges/candies-1
EDIT
After some optimisations, my solution now fails 3 of the test cases (the same ones it was failing before due to timeout). It was not a performance issue
javascript algorithm optimization
1
Try to copy the exact problem statement. The second sentence of your problem description has a very different meaning from the one in challenge.
– SaiBot
Mar 27 at 7:49
Edited! Thanks for noticing that error
– binte
Mar 27 at 7:57
1
The main problem is that you have three nested loops making the runtime something like O(n^3). You should be able to do it in one pass of the data. First calculate the number of candies that each child will eventually end up with. Then scan over the chlidren. Think about it this way: If the first child has k candies below average these k candies have to be transported there. So you will need at least k moves. Now go to the next child, can you get them from there, maybe partially? If not you will need an additional k moves for the first child and on top the candies that child 2 is missing.
– SaiBot
Mar 27 at 8:04
add a comment |
I am trying to solve an hackerrank challenge in JavaScript, and although for most of the test instances my solution performs quite well, I keep getting a timeout for some of them (Hackerrank has it set for 10 seconds for JavaScript challenges). The problem is described below:
There are N children standing in a line. Initially the i-th child has a[i]
candies. Some of the children have more candies than others. You have
to make sure that every student has the same number of candies. In one
operation you can tell one of the children to give a single candy to
the left neighbour, or to the right one. How many operations do you
need to make sure every student has same number of candies? Print the
minimal possible number of operations. The input is a multiline
string, where the first line contains a single integer N, and the next
line contains N space separated integers.
I solved this problem by calculating which number of candies should be given to each and every kid, and then iterate the array containing the number of candies, either grabbing candies from the rightmost positions (in case the child wouldn't have enough), or passing candies to the right position (in case the child would have more than needed)
This is the code I used for the challenge:
function processData(input) /),
n = tmp[0]
tmp.shift() // remove first element from tmp (the N variable)
let s=0, a = tmp.map(function(ai) novo=parseInt(ai, 10);s+=novo;return(novo)),
obj = s/n, ops = 0
for(var i=0; i<n; i++)
if(a[i] > obj)
let moved = a[i]-obj
a[i]-=moved
a[i+1]+=moved
ops+=moved
else
for(var j=i+1; a[i] != obj; j++)
if(a[j]===0)
ops++
else
let moved = Math.min(a[j], obj-a[i])
a[i]+=moved
a[j]-=moved
ops+=moved
//console.log(a)
console.log(ops)
Any idea on what is the problem?
How would you optimise my code?
Link to the challenge : https://www.hackerrank.com/contests/coc1/challenges/candies-1
EDIT
After some optimisations, my solution now fails 3 of the test cases (the same ones it was failing before due to timeout). It was not a performance issue
javascript algorithm optimization
I am trying to solve an hackerrank challenge in JavaScript, and although for most of the test instances my solution performs quite well, I keep getting a timeout for some of them (Hackerrank has it set for 10 seconds for JavaScript challenges). The problem is described below:
There are N children standing in a line. Initially the i-th child has a[i]
candies. Some of the children have more candies than others. You have
to make sure that every student has the same number of candies. In one
operation you can tell one of the children to give a single candy to
the left neighbour, or to the right one. How many operations do you
need to make sure every student has same number of candies? Print the
minimal possible number of operations. The input is a multiline
string, where the first line contains a single integer N, and the next
line contains N space separated integers.
I solved this problem by calculating which number of candies should be given to each and every kid, and then iterate the array containing the number of candies, either grabbing candies from the rightmost positions (in case the child wouldn't have enough), or passing candies to the right position (in case the child would have more than needed)
This is the code I used for the challenge:
function processData(input) /),
n = tmp[0]
tmp.shift() // remove first element from tmp (the N variable)
let s=0, a = tmp.map(function(ai) novo=parseInt(ai, 10);s+=novo;return(novo)),
obj = s/n, ops = 0
for(var i=0; i<n; i++)
if(a[i] > obj)
let moved = a[i]-obj
a[i]-=moved
a[i+1]+=moved
ops+=moved
else
for(var j=i+1; a[i] != obj; j++)
if(a[j]===0)
ops++
else
let moved = Math.min(a[j], obj-a[i])
a[i]+=moved
a[j]-=moved
ops+=moved
//console.log(a)
console.log(ops)
Any idea on what is the problem?
How would you optimise my code?
Link to the challenge : https://www.hackerrank.com/contests/coc1/challenges/candies-1
EDIT
After some optimisations, my solution now fails 3 of the test cases (the same ones it was failing before due to timeout). It was not a performance issue
javascript algorithm optimization
javascript algorithm optimization
edited Mar 27 at 9:16
binte
asked Mar 27 at 7:05
bintebinte
4051 gold badge7 silver badges14 bronze badges
4051 gold badge7 silver badges14 bronze badges
1
Try to copy the exact problem statement. The second sentence of your problem description has a very different meaning from the one in challenge.
– SaiBot
Mar 27 at 7:49
Edited! Thanks for noticing that error
– binte
Mar 27 at 7:57
1
The main problem is that you have three nested loops making the runtime something like O(n^3). You should be able to do it in one pass of the data. First calculate the number of candies that each child will eventually end up with. Then scan over the chlidren. Think about it this way: If the first child has k candies below average these k candies have to be transported there. So you will need at least k moves. Now go to the next child, can you get them from there, maybe partially? If not you will need an additional k moves for the first child and on top the candies that child 2 is missing.
– SaiBot
Mar 27 at 8:04
add a comment |
1
Try to copy the exact problem statement. The second sentence of your problem description has a very different meaning from the one in challenge.
– SaiBot
Mar 27 at 7:49
Edited! Thanks for noticing that error
– binte
Mar 27 at 7:57
1
The main problem is that you have three nested loops making the runtime something like O(n^3). You should be able to do it in one pass of the data. First calculate the number of candies that each child will eventually end up with. Then scan over the chlidren. Think about it this way: If the first child has k candies below average these k candies have to be transported there. So you will need at least k moves. Now go to the next child, can you get them from there, maybe partially? If not you will need an additional k moves for the first child and on top the candies that child 2 is missing.
– SaiBot
Mar 27 at 8:04
1
1
Try to copy the exact problem statement. The second sentence of your problem description has a very different meaning from the one in challenge.
– SaiBot
Mar 27 at 7:49
Try to copy the exact problem statement. The second sentence of your problem description has a very different meaning from the one in challenge.
– SaiBot
Mar 27 at 7:49
Edited! Thanks for noticing that error
– binte
Mar 27 at 7:57
Edited! Thanks for noticing that error
– binte
Mar 27 at 7:57
1
1
The main problem is that you have three nested loops making the runtime something like O(n^3). You should be able to do it in one pass of the data. First calculate the number of candies that each child will eventually end up with. Then scan over the chlidren. Think about it this way: If the first child has k candies below average these k candies have to be transported there. So you will need at least k moves. Now go to the next child, can you get them from there, maybe partially? If not you will need an additional k moves for the first child and on top the candies that child 2 is missing.
– SaiBot
Mar 27 at 8:04
The main problem is that you have three nested loops making the runtime something like O(n^3). You should be able to do it in one pass of the data. First calculate the number of candies that each child will eventually end up with. Then scan over the chlidren. Think about it this way: If the first child has k candies below average these k candies have to be transported there. So you will need at least k moves. Now go to the next child, can you get them from there, maybe partially? If not you will need an additional k moves for the first child and on top the candies that child 2 is missing.
– SaiBot
Mar 27 at 8:04
add a comment |
2 Answers
2
active
oldest
votes
The question is, how many moves do you need to have an avarage count for each children.
For example take this line of children,
1 4 2 7 1
where you start with the first children and look how much items it has and how many items it should have. Take the (absolute) difference for counting the moves and give the first child the average. The next children gets the delta of the first children. In this case after giving two items, it has then two items.
Then look at the next children in the line. Repeat the above and you get the count of moves for all children in a single loop.
children moves
--------------- -----
1 4 2 7 1 2
<3 2> 2 7 1 1
3 <3 1> 7 1 2
3 3 <3 5> 1 2
3 3 3 <3 3>
--------------- -----
7
<x y> denotes a group of changing values
Example 2
children moves
--------------- -----
7 4 2 1 1 4
<3 8> 2 1 1 5
3 <3 7> 1 1 4
3 3 <3 5> 1 2
3 3 3 <3 3>
--------------- -----
15
function processData(input)
var [length, ...values] = input.split(/\n
console.log(processData('5n1 4 2 7 1')); // 7
console.log(processData('5n7 4 2 1 1')); // 15
console.log(processData('3n1 2 3')); // 2
I believe that is what I am already doing!
– binte
Mar 27 at 9:19
really with a single loop? maybe i should add some code ...
– Nina Scholz
Mar 27 at 9:19
Oops this is the same solution as mine +1, it is not the same as @binte's.
– maraca
Mar 27 at 11:47
Thanks for the explanation and for the code :)
– binte
Mar 27 at 12:44
add a comment |
Your solution seems to be O(n^2) but should be solvable in O(n):
function processCandyArray(candies)
let sum = 0, steps = 0, carry = 0
for (let i = 0; i < candies.length; i++)
sum += candies[i]
let avg = sum / candies.length
for (let i = 0; i < candies.length - 1; i++)
carry = candies[i] + carry - avg
steps += carry > 0 ? carry : -carry
return steps
You can just go through the array after calculating the average and at each position you calculate how many candies are carried over (from the left is positive and from the right is negative carry) and sum up the absolute carries.
Thanks for your answer mate, but I'm gonna accept Nina's answer as the correct one because it was the first, and also because of her explanation
– binte
Mar 27 at 12:49
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55371545%2fchildren-candies-hackerrank-challenge-optimising-the-solution%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
The question is, how many moves do you need to have an avarage count for each children.
For example take this line of children,
1 4 2 7 1
where you start with the first children and look how much items it has and how many items it should have. Take the (absolute) difference for counting the moves and give the first child the average. The next children gets the delta of the first children. In this case after giving two items, it has then two items.
Then look at the next children in the line. Repeat the above and you get the count of moves for all children in a single loop.
children moves
--------------- -----
1 4 2 7 1 2
<3 2> 2 7 1 1
3 <3 1> 7 1 2
3 3 <3 5> 1 2
3 3 3 <3 3>
--------------- -----
7
<x y> denotes a group of changing values
Example 2
children moves
--------------- -----
7 4 2 1 1 4
<3 8> 2 1 1 5
3 <3 7> 1 1 4
3 3 <3 5> 1 2
3 3 3 <3 3>
--------------- -----
15
function processData(input)
var [length, ...values] = input.split(/\n
console.log(processData('5n1 4 2 7 1')); // 7
console.log(processData('5n7 4 2 1 1')); // 15
console.log(processData('3n1 2 3')); // 2
I believe that is what I am already doing!
– binte
Mar 27 at 9:19
really with a single loop? maybe i should add some code ...
– Nina Scholz
Mar 27 at 9:19
Oops this is the same solution as mine +1, it is not the same as @binte's.
– maraca
Mar 27 at 11:47
Thanks for the explanation and for the code :)
– binte
Mar 27 at 12:44
add a comment |
The question is, how many moves do you need to have an avarage count for each children.
For example take this line of children,
1 4 2 7 1
where you start with the first children and look how much items it has and how many items it should have. Take the (absolute) difference for counting the moves and give the first child the average. The next children gets the delta of the first children. In this case after giving two items, it has then two items.
Then look at the next children in the line. Repeat the above and you get the count of moves for all children in a single loop.
children moves
--------------- -----
1 4 2 7 1 2
<3 2> 2 7 1 1
3 <3 1> 7 1 2
3 3 <3 5> 1 2
3 3 3 <3 3>
--------------- -----
7
<x y> denotes a group of changing values
Example 2
children moves
--------------- -----
7 4 2 1 1 4
<3 8> 2 1 1 5
3 <3 7> 1 1 4
3 3 <3 5> 1 2
3 3 3 <3 3>
--------------- -----
15
function processData(input)
var [length, ...values] = input.split(/\n
console.log(processData('5n1 4 2 7 1')); // 7
console.log(processData('5n7 4 2 1 1')); // 15
console.log(processData('3n1 2 3')); // 2
I believe that is what I am already doing!
– binte
Mar 27 at 9:19
really with a single loop? maybe i should add some code ...
– Nina Scholz
Mar 27 at 9:19
Oops this is the same solution as mine +1, it is not the same as @binte's.
– maraca
Mar 27 at 11:47
Thanks for the explanation and for the code :)
– binte
Mar 27 at 12:44
add a comment |
The question is, how many moves do you need to have an avarage count for each children.
For example take this line of children,
1 4 2 7 1
where you start with the first children and look how much items it has and how many items it should have. Take the (absolute) difference for counting the moves and give the first child the average. The next children gets the delta of the first children. In this case after giving two items, it has then two items.
Then look at the next children in the line. Repeat the above and you get the count of moves for all children in a single loop.
children moves
--------------- -----
1 4 2 7 1 2
<3 2> 2 7 1 1
3 <3 1> 7 1 2
3 3 <3 5> 1 2
3 3 3 <3 3>
--------------- -----
7
<x y> denotes a group of changing values
Example 2
children moves
--------------- -----
7 4 2 1 1 4
<3 8> 2 1 1 5
3 <3 7> 1 1 4
3 3 <3 5> 1 2
3 3 3 <3 3>
--------------- -----
15
function processData(input)
var [length, ...values] = input.split(/\n
console.log(processData('5n1 4 2 7 1')); // 7
console.log(processData('5n7 4 2 1 1')); // 15
console.log(processData('3n1 2 3')); // 2
The question is, how many moves do you need to have an avarage count for each children.
For example take this line of children,
1 4 2 7 1
where you start with the first children and look how much items it has and how many items it should have. Take the (absolute) difference for counting the moves and give the first child the average. The next children gets the delta of the first children. In this case after giving two items, it has then two items.
Then look at the next children in the line. Repeat the above and you get the count of moves for all children in a single loop.
children moves
--------------- -----
1 4 2 7 1 2
<3 2> 2 7 1 1
3 <3 1> 7 1 2
3 3 <3 5> 1 2
3 3 3 <3 3>
--------------- -----
7
<x y> denotes a group of changing values
Example 2
children moves
--------------- -----
7 4 2 1 1 4
<3 8> 2 1 1 5
3 <3 7> 1 1 4
3 3 <3 5> 1 2
3 3 3 <3 3>
--------------- -----
15
function processData(input)
var [length, ...values] = input.split(/\n
console.log(processData('5n1 4 2 7 1')); // 7
console.log(processData('5n7 4 2 1 1')); // 15
console.log(processData('3n1 2 3')); // 2
function processData(input)
var [length, ...values] = input.split(/\n
console.log(processData('5n1 4 2 7 1')); // 7
console.log(processData('5n7 4 2 1 1')); // 15
console.log(processData('3n1 2 3')); // 2
function processData(input)
var [length, ...values] = input.split(/\n
console.log(processData('5n1 4 2 7 1')); // 7
console.log(processData('5n7 4 2 1 1')); // 15
console.log(processData('3n1 2 3')); // 2
edited Mar 27 at 12:17
answered Mar 27 at 8:15
Nina ScholzNina Scholz
221k16 gold badges132 silver badges199 bronze badges
221k16 gold badges132 silver badges199 bronze badges
I believe that is what I am already doing!
– binte
Mar 27 at 9:19
really with a single loop? maybe i should add some code ...
– Nina Scholz
Mar 27 at 9:19
Oops this is the same solution as mine +1, it is not the same as @binte's.
– maraca
Mar 27 at 11:47
Thanks for the explanation and for the code :)
– binte
Mar 27 at 12:44
add a comment |
I believe that is what I am already doing!
– binte
Mar 27 at 9:19
really with a single loop? maybe i should add some code ...
– Nina Scholz
Mar 27 at 9:19
Oops this is the same solution as mine +1, it is not the same as @binte's.
– maraca
Mar 27 at 11:47
Thanks for the explanation and for the code :)
– binte
Mar 27 at 12:44
I believe that is what I am already doing!
– binte
Mar 27 at 9:19
I believe that is what I am already doing!
– binte
Mar 27 at 9:19
really with a single loop? maybe i should add some code ...
– Nina Scholz
Mar 27 at 9:19
really with a single loop? maybe i should add some code ...
– Nina Scholz
Mar 27 at 9:19
Oops this is the same solution as mine +1, it is not the same as @binte's.
– maraca
Mar 27 at 11:47
Oops this is the same solution as mine +1, it is not the same as @binte's.
– maraca
Mar 27 at 11:47
Thanks for the explanation and for the code :)
– binte
Mar 27 at 12:44
Thanks for the explanation and for the code :)
– binte
Mar 27 at 12:44
add a comment |
Your solution seems to be O(n^2) but should be solvable in O(n):
function processCandyArray(candies)
let sum = 0, steps = 0, carry = 0
for (let i = 0; i < candies.length; i++)
sum += candies[i]
let avg = sum / candies.length
for (let i = 0; i < candies.length - 1; i++)
carry = candies[i] + carry - avg
steps += carry > 0 ? carry : -carry
return steps
You can just go through the array after calculating the average and at each position you calculate how many candies are carried over (from the left is positive and from the right is negative carry) and sum up the absolute carries.
Thanks for your answer mate, but I'm gonna accept Nina's answer as the correct one because it was the first, and also because of her explanation
– binte
Mar 27 at 12:49
add a comment |
Your solution seems to be O(n^2) but should be solvable in O(n):
function processCandyArray(candies)
let sum = 0, steps = 0, carry = 0
for (let i = 0; i < candies.length; i++)
sum += candies[i]
let avg = sum / candies.length
for (let i = 0; i < candies.length - 1; i++)
carry = candies[i] + carry - avg
steps += carry > 0 ? carry : -carry
return steps
You can just go through the array after calculating the average and at each position you calculate how many candies are carried over (from the left is positive and from the right is negative carry) and sum up the absolute carries.
Thanks for your answer mate, but I'm gonna accept Nina's answer as the correct one because it was the first, and also because of her explanation
– binte
Mar 27 at 12:49
add a comment |
Your solution seems to be O(n^2) but should be solvable in O(n):
function processCandyArray(candies)
let sum = 0, steps = 0, carry = 0
for (let i = 0; i < candies.length; i++)
sum += candies[i]
let avg = sum / candies.length
for (let i = 0; i < candies.length - 1; i++)
carry = candies[i] + carry - avg
steps += carry > 0 ? carry : -carry
return steps
You can just go through the array after calculating the average and at each position you calculate how many candies are carried over (from the left is positive and from the right is negative carry) and sum up the absolute carries.
Your solution seems to be O(n^2) but should be solvable in O(n):
function processCandyArray(candies)
let sum = 0, steps = 0, carry = 0
for (let i = 0; i < candies.length; i++)
sum += candies[i]
let avg = sum / candies.length
for (let i = 0; i < candies.length - 1; i++)
carry = candies[i] + carry - avg
steps += carry > 0 ? carry : -carry
return steps
You can just go through the array after calculating the average and at each position you calculate how many candies are carried over (from the left is positive and from the right is negative carry) and sum up the absolute carries.
edited Mar 27 at 12:05
answered Mar 27 at 11:26
maracamaraca
6,0033 gold badges16 silver badges40 bronze badges
6,0033 gold badges16 silver badges40 bronze badges
Thanks for your answer mate, but I'm gonna accept Nina's answer as the correct one because it was the first, and also because of her explanation
– binte
Mar 27 at 12:49
add a comment |
Thanks for your answer mate, but I'm gonna accept Nina's answer as the correct one because it was the first, and also because of her explanation
– binte
Mar 27 at 12:49
Thanks for your answer mate, but I'm gonna accept Nina's answer as the correct one because it was the first, and also because of her explanation
– binte
Mar 27 at 12:49
Thanks for your answer mate, but I'm gonna accept Nina's answer as the correct one because it was the first, and also because of her explanation
– binte
Mar 27 at 12:49
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55371545%2fchildren-candies-hackerrank-challenge-optimising-the-solution%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Try to copy the exact problem statement. The second sentence of your problem description has a very different meaning from the one in challenge.
– SaiBot
Mar 27 at 7:49
Edited! Thanks for noticing that error
– binte
Mar 27 at 7:57
1
The main problem is that you have three nested loops making the runtime something like O(n^3). You should be able to do it in one pass of the data. First calculate the number of candies that each child will eventually end up with. Then scan over the chlidren. Think about it this way: If the first child has k candies below average these k candies have to be transported there. So you will need at least k moves. Now go to the next child, can you get them from there, maybe partially? If not you will need an additional k moves for the first child and on top the candies that child 2 is missing.
– SaiBot
Mar 27 at 8:04