Sort by

recency

|

2605 Discussions

|

  • + 0 comments
    def pickingNumbers(a):
        a.sort()
        ml = 0
        for i in range(len(a)):
            la = [a[i]]
            for j in range(i+1, len(a)):
                if abs(a[i]-a[j]) <= 1:
                    la.append(a[j])
            
            print(la)
            if len(la) > ml:
                ml = len(la) 
                
        return ml
                
                
    
  • + 0 comments

    Flag array method (write in kotlin):

    fun pickingNumbers(a: Array<Int>): Int {
        // Write your code here
        var maxLength = 1
        var maxValue = 0
        val frequencies = MutableList(100) { 0 }
    
        a.forEach { num ->
            maxValue = Math.max(num, maxValue)
            frequencies[num]++
        }
    
        for (i in 1..maxValue) {
            val subListLength = frequencies[i] + frequencies[i - 1]
            maxLength = Math.max(maxLength, subListLength)
        }
    
        return maxLength
    }``
    
  • + 0 comments

    Simple unsorted n-squared solution.

    // Write your code here
        int maxcount = 0;
        for (int i = 0; i < a.size(); i++) {
            int v = a.get(i);
            int count = 1;
            for (int j = 0; j < a.size(); j++) {
                if (i == j) {
                    continue;
                }   
                int q = a.get(j);
                if (v == q || v == q - 1) {
                    count++;
                }   
            }   
            if (count > maxcount) {
                maxcount = count;
            }
        return maxcount;
    }
    
  • + 0 comments
    function pickingNumbers(a: number[]): number {
        
        // sort arr in ascding order
        a.sort((x,y)=>x-y);
        
        let ans = 0;
        let window_start = 0;
        
        for (let window_end = 0; window_end < a.length; window_end++) {
            
            while (a[window_end] - a[window_start] > 1) {
                window_start ++;
            }
            
             const window_size = window_end - window_start +1;
             
             ans = Math.max(window_size, ans);
        }
        
        return ans;
    }
    
  • + 0 comments

    As many exercises on this site, the description of the problem is misleading: it gives you the impression that data in the array have to stay unordered... but in reality the problem expects for you to sort the array.

    def pickingNumbers(a):
        a.sort()
        cnt = 1
        cmx = 0
        i = 1
        s = a[0]
        while i<len(a):
            t = a[i]
            if abs(t-s)<=1:
                cnt += 1
            else:
                s = a[i]
                cmx = max(cmx,cnt)
                cnt = 1
            i += 1
        if i == len(a):
            cmx = max(cmx, cnt)
        return cmx