We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Looks good to me. But you haven't shown how you update pb so I can't understand completely.
One note, it seems to me that pb=(b>pb)?b:pb; is another way to write pb=max(b,pb);. I note that using algebra, pb+c>c is equivalent to pb>0, which is slightly more efficient. Similarly pb+c>pb is the same as c>0.
On the other hand, when is is not the best sum. you will need to update pb. When there are all negative elements, pb is undefined by the problem statement; either pb = 0 because the shortest array is 0 length, or it's equal to the smallest element, because the shortest array is 1 length.
I think that you used the second definition, right?
For noncontiguous with at least one positive element, similar to @maximshen's solution above, just needs to sum all positive elements. That one is easy, it looks like: for(int x:arr) { b = b + (c>0)?c:0; }
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
The Maximum Subarray
You are viewing a single comment's thread. Return to all comments →
Looks good to me. But you haven't shown how you update pb so I can't understand completely.
One note, it seems to me that
pb=(b>pb)?b:pb;
is another way to writepb=max(b,pb);
. I note that using algebra,pb+c>c
is equivalent topb>0
, which is slightly more efficient. Similarlypb+c>pb
is the same asc>0
.On the other hand, when is is not the best sum. you will need to update pb. When there are all negative elements, pb is undefined by the problem statement; either pb = 0 because the shortest array is 0 length, or it's equal to the smallest element, because the shortest array is 1 length.
I think that you used the second definition, right?
For noncontiguous with at least one positive element, similar to @maximshen's solution above, just needs to sum all positive elements. That one is easy, it looks like:
for(int x:arr) { b = b + (c>0)?c:0; }