# Breaking the Records

# Breaking the Records

lahouari + 9 comments My java submission:

static int[] getRecord(int[] s) { int highest, lowest; highest = lowest = s[0]; int[] result = new int[2]; for (int s_i = 1; s_i < s.length; s_i++) { if (s[s_i] > highest) { highest = s[s_i]; ++result[0]; } else if (s[s_i] < lowest) { lowest = s[s_i]; ++result[1]; } } return result; }

JulioLeme + 2 comments Show, my solution is very like with yours, nice to see the similarities, see it:

`static int[] getRecord(int[] s){ int[] result = new int[2]; int countMax=0, countMin=0 ,max = s[0], min = s[0]; for(int i=1; i< s.length; i++){ if(s[i] > max){ max = s[i]; countMax++; } if(s[i] < min){ min = s[i]; countMin++; } } result[0] = countMax; result[1] = countMin; return result; }`

work30 + 1 comment "else if" is slightly better than if, if because both cannot be true Also pre-increment slightly better than post-increment I think?

HTH

enricogiurin + 0 comments or you can add a

*continue*after the first*if*

umangsomtiya8083 + 1 comment # include

# include

using namespace std;

int main() { int n; cin>>n; int i,j,score[n],min,max,u=0,v=0; for(i=0;i>score[n]; } max=score[0]; min=score[0]; for(j=0;j

`} for(j=0;j<n;j++) { if( min>score[j]) { v++; min=score[j]; } } cout<<u<<" "<<v;`

} this code is not giving correct answer and logic is simmilar to your code. can you plz explain why?

PedroStu + 0 comments Why are you doing it with interger array? Try it using vector, as given in the question. If you change the format of the answer/method, you are skipping the learning part. Vectors are really very powerful as compared to any other array. I know this will give you many other troubles like the old 'Segmentation Fault'. But this is what is expected once you are advancing in the programming world. this can be a way:

`vector<int> breakingRecords(vector<int> scores) { vector<int> Minmax(2); //VERY CRUCIAL FOR AVOIDING SEGMENTATION FAULT int i=0; long long int Min=0, Max=0; Max = scores.at(i); Min = scores.at(i);i++; while (i< scores.size()) { if(scores.at(i) > Max) { Max = scores.at(i);Minmax.at(0)++; } else if(scores.at(i) < Min) { Min = scores.at(i);Minmax.at(1)++; } i++; } return(Minmax); }`

alphazygma + 0 comments Heh heh heh, my solution is very similar to yours and Julio's

static int[] getRecord(int[] s){ if (s.length == 0) { return new int[2]; } int lowest = s[0]; int highest = s[0]; int lowestCount = 0; int highestCount = 0; for (int score : s) { if (score < lowest) { lowest = score; lowestCount++; } else if (score > highest) { highest = score; highestCount++; } } return new int[]{highestCount, lowestCount}; }

hiljusti + 3 comments Mine (in JS) was very similar:

function getRecord(games) { let most = games[0]; let least = games[0]; let dMost = 0; let dLeast = 0; for (const score of games) { if (most < score) { most = score; dMost++; } else if (score < least) { least = score; dLeast++; } } return [dMost, dLeast]; }

armadillo_ko167 + 0 comments it's min (in js)

function breakingRecords(score) { const scoreLength = score.length; let mostScore = score[0]; let worstScore = score[0]; let mostScoreIncreased = 0; let worstScoreDecreased = 0; for(let i = 0; i < scoreLength; i++){ const curScore = score[i]; if(mostScore < curScore){ mostScore = curScore; mostScoreIncreased++; } if(worstScore > curScore){ worstScore = curScore; worstScoreDecreased++; } } return [mostScoreIncreased, worstScoreDecreased]; }

anishd19 + 0 comments [deleted]afreen08neela + 1 comment what is the time limit and memory limit given by hacker rank for this problem?

davidheisnam + 0 comments [deleted]

cu_16bcs2416 + 1 comment you could have used break in first if stmt as is would reduce time complexity!

enricogiurin + 0 comments You mean a

*continue*, not a*break*.

rabiyaaruba + 0 comments evn...i hv done d same code...bt i'm getting error.....at the result initialization.....can u plz help me..!

Thinkster + 0 comments Ruby Implementation:

def breaking_records(scores) min_el = max_el = scores[0] min_count, max_count = 0, 0 (1...scores.length).each do |score| min, max = scores[0..score].min, scores[0..score].max if min < min_el min_el, min_count = min, (min_count += 1) elsif max > max_el max_el, max_count = max, (max_count += 1) end end [max_count, min_count] end

coder_aky + 2 comments # 100 % working ,Simple and easy :-)

*In Python 3 :*n,a= int(input()),list(map(int, input().split())) max=min=a[0];c1=c2=0 for i in range(1,n): if a[i]>max: c1+=1;max=a[i] if a[i]<min: c2+=1;min=a[i] print(c1,c2,sep=' ')

CyberZii + 0 comments Beautiful!

shreeshreya17 + 0 comments what's the need of taking array for result..is there not a way to print min and max directly.

marinskiy + 5 comments Here is

**Python 3**solution from my HackerrankPractice repository:def breaking_records(score): min = max = score[0] min_count = max_count = 0 for i in score[1:]: if i > max: max_count += 1 max = i if i < min: min_count += 1 min = i return max_count, min_count n = int(input()) score = list(map(int, input().split())) print(*breaking_records(score))

Feel free to ask if you have any questions :)

mahamadbilal696 + 2 comments why you added * in the print statement.... please explain me.

print(*breaking_records(score))

TheSoleCodr + 0 comments [deleted]TheSoleCodr + 0 comments Addding * in print statement will print your answer as

1 2 3 4 5

and will print your answer like this when you do not use it

[ 1, 2, 3, 4, 5 ]

Thinkster + 0 comments How about Ruby Implementation?

def breaking_records(scores) min_el = max_el = scores[0] min_count = max_count = 0 (1...scores.length).each do |score| min, max = scores[0..score].min, scores[0..score].max if min < min_el min_el, min_count = min, (min_count += 1) elsif max > max_el max_el, max_count = max, (max_count += 1) end end [max_count, min_count] end

4573r14 + 0 comments I liked this solution

krishnansr_siva + 0 comments I feel that the below solution is more 'pythonic' but obivously not well optimized

def breaking_records(score):

hs = [ i for i,item in enumerate(scores[1:]) if item>max(scores[0:i+1]) ]

ls = [ i for i,item in enumerate(scores[1:]) if item

return [len(hs), len(ls)]

robmcortez + 0 comments Just FYI,

`min`

and`max`

are built in functions in python. You probably don't want to use them for variable names.

abhiarora1137 + 1 comment My code is working properly in editor, but i'm getting error here , "result.join() is not a function". Code language Javascript.

santosh532 + 1 comment Looks like you have to return in array format eg: [max, min]

seantbmorgan + 0 comments Good lookin' out.

helggg + 1 comment python:

def breakingRecords(scores): m = l = scores[0] cm = cl = 0 for i in scores: if i > m: cm += 1 m = i if i < l: cl += 1 l = i return cm, cl

vaishnavi_msn + 3 comments ive written a similar one but this code is solving only 11/15 cases. for n>1000 its not able to solve.idk why

def breakingRecords(scores): p=q=scores[0] g=l=0 for i in scores: if(i>p): p=i g=g+1 if(i<q): q=i l=l+1 g=str(g) l=str(l) z=[g,l] return(''.join(z))

catch22kn + 0 comments I had a similar issue. For some reason, changing my returning of a formatted string to:

return highCount, lowCount

worked for the ones that were giving me an issue.

yypark_mgiy + 0 comments [deleted]ammadrocks + 0 comments same here i am also using python 3

itsbaldeep + 2 comments **JavaScript**// Preparing variables let [ hi, lo ] = [ scores[0], scores[0] ]; let [ max, min ] = [ 0, 0 ]; // Calculating for (let i = 1; i < scores.length; i++) { if (scores[i] > hi) { hi = scores[i]; max++; } if (scores[i] < lo) { lo = scores[i]; min++; } } //Returning return [ max, min ];

mdjonesonly310 + 0 comments Beautiful

gary_l_hewitt + 1 comment The only advantage is that it also gives the record of each time the record is broken.

function breakingRecords(scores) { var h = [scores[0]]; var l = [scores[0]]; scores.forEach( e=> { if (e>h.reduce((a,c)=>Math.max(a,c))) h.push(e); if (e<l.reduce((a,c)=>Math.min(a,c))) l.push(e); }); return [h.length-1,l.length-1]; }

NaveenKashyap + 1 comment if you are in an interview you don't wanna use built in functions

gary_l_hewitt + 1 comment Why not?

NaveenKashyap + 1 comment If you use a library function then it defeats the primary objective of testing your competency.

gary_l_hewitt + 0 comments Perhaps competency is using certain language features? Not trying to be a troll but one could say that syntax like:

let [ hi, lo ] = [ scores[0], scores[0] ];

is as much built-in as

`Math.max()`

or`Array.reduce()`

which access javascript type-primitive methods.The loop method is much more efficient, however, since it maintains the min & max rather than recalculating it every time w the

`reduce()`

. I think I managed to create a very nice example of Schlemiel the painter's algorithm

madhudskumar + 6 comments def getRecord(scores): ls = hs = s[0]; lc = hc = 0; for score in scores: if(score > hs): hs = score; hc += 1; if(score < ls): ls = score; lc += 1; return [hc, lc]

This worked

esyray15 + 0 comments You could have just wrote the

`return`

statment as`return hc, lc`

david_mathis_ii + 0 comments why iterate through s[0] if you already assigned it? you could shave this like:

fore score in scores[1:]:

asd_shivam98 + 0 comments # include

using namespace std; int main() { int n,s[n]; cin >> n; cin >> s[0]; int c=0,d=0; int a=s[0]; int b=s[0]; for(int i=1;i> s[i]; if(s[i]>a) { a=s[i]; c++; } else if(s[i] cout << c << " " << d; return 0; }

[deleted] + 1 comment My code is almost similar to yours. But there are apparently problems with mine. Could you please point them out?

n = int(raw_input().strip()) score = list(map(int, raw_input().strip().split(' '))) hb, lb = 0, -1 a = score[0] for b in score: if (b>a): a = b hb +=1 for c in score: if (c<=a): a = c lb +=1 print hb, print lb

lrkoehler77 + 1 comment Your not returning correctly. Do it like:

**return hb,lb**mahamadbilal696 + 0 comments that's not a problem... he assign the initial value of lb = -1 instead of lb = 0

chinmay43 + 2 comments My logic is almost same, But this code is giving runtime error in test case 10. what can be the issue ?

def breakingRecords(score): min_1 = score[0] max_1 = score[0] min_brk = 0 max_brk = 0 if len(score) < 2: return 0 for i in range(len(score)): if (score[i] < min_1): min_brk += 1 min_1 = score[i] elif(score[i] > max_1): max_brk += 1 max_1 = score[i] else: max_brk = max_brk min_brk = min_brk i += 1 return(max_brk, min_brk)

tylercjulian + 1 comment I just tested your code. The issue is with this line:

if len(score) < 2: return 0

Remove that line and your code passes the tests.

Also, for efficiency, there is no need for the

`i += 1`

, since the for loop automatically increments i. You could also iterate directly through the scores instead of having to rely on using a range for index numbers. The parent example uses this method.chinmay43 + 1 comment Thanks a lot :-)

tylercjulian + 0 comments You are welcome :)

sshayann7 + 0 comments [deleted]

mumbaikar + 0 comments We can do directly in main function -

`public static void main(String[] args) { int min_record = 0; int max_record = 0; int worst = 0; int best = 0; int curr_record = 0; Scanner in = new Scanner(System.in); int n = in.nextInt(); for(int s_i=0; s_i < n; s_i++){ curr_record = in.nextInt(); if(s_i == 0) { min_record = curr_record; max_record = curr_record; } if(s_i > 0) { if(curr_record < min_record) { min_record = curr_record; worst++; } else if (curr_record > max_record) { max_record = curr_record; best++; } } } System.out.println(best + " " + worst); System.out.println(""); in.close(); }`

sgawlik + 5 comments I haven't found a C solution that actually uses the code as it is given. I wanted something that doesn't change any of the code but still returns the result in the format the author intended. If you follow my comments you can see how to pass values between functions in C. I hope this helps people who were also unsatisfied with solutions that were written entirely in the main function or those who've wondered what to do about result_size in the C starter code of so many of these early exercises.

#define HOWMANYRESULTS 2 int* getRecord(int s_size, int* s, int *result_size) { // set best and worst to first game int worst = s[0]; int best = s[0]; // let main know how many results you'll print *result_size = HOWMANYRESULTS; // allocate heap space for the results and initialize to 0 int *result = malloc(sizeof(int) * *result_size); result[0] = 0; result[1] = 0; // start loop from the second game for (int i = 1; i < s_size; i++) { if (s[i] > best) { // increase counter for best and reset best result[0]++; best = s[i]; } if (s[i] < worst) { // increase counter for worst and reset worst result[1]++; worst = s[i]; } } // return the address of the results on heap to main return result; }

I'm guessing that other people have also struggled with the common format for all C starter code so I have added some comments to the part of main that I found tricky:

// how many things will be printed int result_size; // call helper function, expect implementer to return // an int pointer (to the results) and set result_size int* result = getRecord(n, s, &result_size); for(int i = 0; i < result_size; i++) { // when i = 0 this evaluates to 0 which is same as // false and we don't print a space if (i) { printf(" "); } // on every round through the loop print another result printf("%d", result[i]); }

I know that allocating space on the heap is not as efficient/fast in the real world as just doing it all in main or printing in getRecord, my focus was on using the starter code and practicing with passing values between functions in C. Solution is O(n) runtime and O(1) space.

lee_rw_cs + 0 comments I like your code comment, I always forget to write documentation, sigh

rajputnisarg17 + 0 comments thanks

prusovigor + 0 comments You can also declare result as a static variable instead of using malloc, this will intialize it with zeros and it will still be accessible after return from function.

AzizStark + 0 comments int main(){ long int arra[2000],n,i,j,haa=0,great=0; scanf("%ld",&n); for(i=0;i<n;i++){ scanf("%ld", &arra[i]); } //========================================= great=arra[0]; for(i=0;i<n;i++){ for(j=1;j<n+1;j++){ if(great<arra[j]) { great=arra[j]; haa=haa+1; } } } printf("%ld", haa); //========================================= haa=0; great=arra[0]; for(i=0;i<n;i++){ for(j=0;j<n;j++){ if(great>arra[j]) { great=arra[j]; haa=haa+1; } } } printf("% ld", haa); return 0; }

Joe_08 + 0 comments Hello sgawlik! Could please explain how *result_size gets the value HOWMANYRESULTS? and also what is the purpose of doing so?....Thank you for your clear solution using C.

sghaida + 1 comment Scala Solution

var res = score.foldLeft((0,0),(score(0),score(0))){ case (acc, c) => c match { case c if c > acc._2._1 => ((acc._1._1+1,acc._1._2),(c,acc._2._2)) case c if c < acc._2._2 => ((acc._1._1, acc._1._2+1),(acc._2._1,c)) case _=> acc } } println(s"${res._1._1} ${res._1._2}")

andtorg + 0 comments Very nice!

That's mine with foldLeft as well: purely functional but with some boilerplate.

class Acc (val min: Int, val max: Int, val nMin: Int, val nMax: Int) object Acc { def apply(a: Int, b: Int, c: Int, d: Int) = new Acc(a,b,c,d) } def count(acc: Acc, elem: Int): Acc = if ( elem > acc.max ) Acc(acc.min, elem, acc.nMin, acc.nMax + 1) else if ( elem < acc.min ) Acc(elem, acc.max, acc.nMin + 1, acc.nMax) else Acc(acc.min, acc.max, acc.nMin, acc.nMax) val res = l.tail.foldLeft(Acc(l.head, l.head, 0, 0))(count)

liu00861 + 0 comments I am wondering why this failed

def breakingRecords(scores): max_score = scores[0] min_score = scores[0] high = 0 low = 0 for idx in range(1,len(scores)): if scores[idx] > max_score: high+=1 max_score = scores[idx] elif scores[idx] < min_score: low += 1 min_score = scores[idx] return str(high) + str(low)

Thanks!

Sort 696 Discussions, By:

Please Login in order to post a comment