Loading...

Sort 332 Discussions, By:

  • lahouari + 4 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 + 1 comment

      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;
          }
      
      • MS
        work30 + 0 comments

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

        HTH

    • 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 + 1 comment

      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];
      }
      
      • KK
        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];
        	        }
        
    • C
      cu_16bcs2416 + 0 comments

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

  • 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.

    • L
      lee_rw_cs + 0 comments

      I like your code comment, I always forget to write documentation, sigh

    • NR
      rajputnisarg17 + 0 comments

      thanks

    • IP
      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;
      }
      
    • JK
      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.

  • madhudskumar + 5 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

    • JG
      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:]:
      
    • SS
      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; }

    • AA
      maxim_marquez + 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 + 0 comments

        Your not returning correctly. Do it like: return hb,lb

    • 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)
      
      • TJ
        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 :-)

          • TJ
            tylercjulian + 0 comments

            You are welcome :)

      • AK
        anna_kor + 1 comment

        Although not incorrect, this part is not necessary in the code:

        else:
                    max_brk = max_brk
                    min_brk = min_brk
        
        • chinmay43 + 0 comments

          True ! thanks :-)

  • JB
    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();
    }
    
  • tevyt + 1 comment

    Test case 5 has an integer with a leading 0 is this intentional?

    • AK
      ankurk007 + 0 comments

      Yes, its intentional.

  • ser_zhile + 0 comments

    Hi guys, here is mine JS solution:

    let hiBreak = 0;
    let lowBreak = 0;
    
    score.reduce((agg, cur)=> {
    	if(cur > agg[0]) {
    		++hiBreak;
    		agg[0] = cur;
    	}
    	else if(cur < agg[1]){
    		++lowBreak;
    		agg[1] = cur;
    	}
    
    	return agg;        
    },[score[0], score[0]])
    
    return [hiBreak, lowBreak];
    
  • L
    Lunaabel9 + 0 comments

    Here's my C++ version:

    vector<int> breakingRecords(vector<int> score) {
        int min=score[0];
        int max=score[0];
        vector<int> myreturn = {0,0};
        for(int i=1;i<score.size();i++){
            if(score[i]>max){
                myreturn[0]+=1;
                max = score[i];
            }
            else if(score[i]<min){
                myreturn[1]+=1;
                min = score[i];
            }
        }
        return myreturn;
    }
    
  • MR
    hellomici + 0 comments

    simple Python2

    def breakingRecords(lst):
        highest = len(set([max(lst[:(num+1)]) for num, i in enumerate(lst) if lst.index(max(lst[:(num+1)])) != 0]))
        lowest = len(set([min(lst[:(num+1)]) for num, i in enumerate(lst) if lst.index(min(lst[:(num+1)])) != 0]))
    
        return highest, lowest
    
  • 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)
      
  • chand87 + 2 comments

    Test case 11

    Input

    5 100000000 100000000 10000000 10000000 1000000

    Output 0 2

    Code: For..... { if (s[s_i] > max) { max = s[s_i]; max_count++; }

        if (s[s_i] < min)
        {
            min = s[s_i];
            min_count++;
        }
    }
    

    Same is coming in my code when i Test against custom input. What is the problem anyone please?

    • SG
      ghosh_saikat4000 + 3 comments

      I am getting the same problem ... Did you find the solution ?

      for(i = 1; i <= no_of_games; i++)
      {
          scanf("%d", &current_score);
      
          if(current_score > maximum)
          {
              maximum = current_score; maximum_changes++; 
          }
          if(current_score < minimum)
          {
              minimum = current_score; minimum_changes++;
          }
      }
      

      The output comes when I test it on computer and custom input but it is not getting accepted.

      • chand87 + 1 comment

        I found that I was downloading wrong test case. My other TC (below 11) was getting failed but i was checking this one.

        Please recheck.

        • SG
          ghosh_saikat4000 + 1 comment

          Thanks. I did the same mistake.

          • chand87 + 0 comments

            lol :)

      • positivedeist_07 + 1 comment

        Hey my code is similar to this, but its not passing the test cases (wrong output). Whats the problem?

        • SG
          ghosh_saikat4000 + 1 comment

          I can't tell without seeing your code ... Post it. But, a common mistake is setting the initial value of max to 0, instead of -1 (because the input can be 0).

          • positivedeist_07 + 1 comment

            Yeah buddy, I found out where I went wrong and cleared all the test cases ;) thank you!!

            • SG
              ghosh_saikat4000 + 1 comment

              Haha ... Was your mistake also that maximum was initialised to 0 and not - 1 ?

              • positivedeist_07 + 2 comments

                Nope. I did with array. I didn't initialize the max and min to the first elements of the array (stupid me! i initialized to max=0 and min=0). Having found the error, I added an if block for that :) My for loop..

                for(i=0;i<n;i++)
                        {
                        cin>>score[i];
                        if(i==0)
                            {
                            max=score[0];
                            min=score[0];
                        }
                        else
                            {
                        if(score[i]>max)
                            {
                            max=score[i];
                            high++;
                           }
                        if(score[i]<min)
                            {
                            min=score[i];
                            low++;
                            }
                          }
                    }
                
                • SG
                  ghosh_saikat4000 + 2 comments

                  Okay ... No problem. You can still do it with initialisation if you don't want an additional if block to make the code simpler. Initialise min to INFINITY, where INFINITY is a macro constant equal to 1e7 + 1, in our case and max is -1. This automatically ensures max and min become the first element of the array.

                  The only additional care needed with my approach is that minimum changes and maximum changes are initialised to -1, so that the first element is not counted. Here's my code.

                  #include <stdio.h>
                  
                  #define INFINITY 100000001
                  
                  int main() 
                  {
                      int no_of_games, current_score, minimum = INFINITY, maximum = -1, minimum_changes = -1, maximum_changes = -1, i; 
                      scanf("%d",&no_of_games);
                      for(i = 1; i <= no_of_games; i++)
                      {
                          scanf("%d", &current_score);
                  
                          if(current_score > maximum)
                          {
                              maximum = current_score; maximum_changes++; 
                          }
                          if(current_score < minimum)
                          {
                              minimum = current_score; minimum_changes++;
                          }
                      }
                  
                      printf("%d %d\n",maximum_changes, minimum_changes);
                      return 0;
                  }
                  
                  • positivedeist_07 + 0 comments

                    Whoa. Okay, buddy :) I get it now. Thank you for your time!!

                  • shubh_gupta + 0 comments

                    With all respect Sir, I don't understand concept initializing of Max : -1 and Min : INFINITY. I think problem clearly states to compare scores in relation to score of very first game. So, MIN = MAX = score[0] will initialize them to let comparision begin in respect to first score. Correct me if I am wrong!

                • anand2000 + 0 comments

                  I am writng same logic but getting timed out error.

      • akhilgautam123 + 0 comments

        https://www.hackerrank.com/challenges/breaking-best-and-worst-records/forum/comments/321322

    • akhilgautam123 + 0 comments

      https://www.hackerrank.com/challenges/breaking-best-and-worst-records/forum/comments/321322