Sort by

recency

|

746 Discussions

|

  • + 0 comments

    very simple and uderstable solution with cpp

    string fairRations(vector B) {

    int key=0;
    
    for(int i = 0;i < B.size()-1;i++){ // because lin last element we have to do other operation
        if(i == B.size()-1){  //this is for last element only
            if(B[i] % 2!=0){
                 B[i]++;
                 B[i-1]++;
            }
    
        }
        if( B[i] % 2 !=0){
            B[i]++;
            B[i+1]++;
            key+=2;
    
        }
    }
    bool flag = 1;
    
    for(int i = 0;i < B.size() ; i++){
        if(B[i] % 2!=0){
            flag=0;
            break;
        }
    }
    
    
    if( flag ==0){
        return "NO";
    }
    else{
        return to_string(key);
    }
    

    }

  • + 0 comments
    public static String fairRations(List<Integer> B) {
        List<Integer> ration = new ArrayList<>(B);
        int count = 0;
        for(int i=0 ;i< ration.size()-1; i++) {
            if(ration.get(i) % 2 == 0) continue;
            if(ration.get(i) % 2 != 0) {
                ration.set(i, ration.get(i)+1);
                ration.set(i+1, ration.get(i+1)+1);
                count += 2;
            }
        }
        if(ration.get(ration.size()-1)%2 != 0) return "NO";
        return ""+count;
    }    
    
  • + 1 comment

    Here is problem solution in PYthon, Java, C++, C and Javascript - https://programmingoneonone.com/hackerrank-fair-rations-problem-solution.html

  • + 0 comments

    Here is my c++ solution: you can watch the explanation here : https://youtu.be/pAzUgM52d60

    string fairRations(vector<int> B) {
        int res = 0;
        for(int i = 0; i < B.size() - 1; i++){
            if(B[i] % 2 == 1){
                B[i+1]++;
                res+=2;
            }
        }
        return B[B.size() - 1] % 2 == 0 ? to_string(res) : "NO";
    }
    

    Whithout the if

    string fairRations(vector<int> B) {
        int res = 0;
        for(int i = 0; i < B.size() - 1; i++){
            B[i+1] += B[i] % 2;
            res += B[i] % 2;
        }
        return B[B.size() - 1] % 2 == 0 ? to_string(res*2) : "NO";
    }
    
  • + 0 comments
    def fairRations(B):
        count=0
        # Write your code here
        def isEvens(arr):
            for i in arr:
                if i%2 != 0:
                    return False
            return True
        for j in range(len(B)):
            if B[j] % 2 != 0:
                if j == len(B)-1:
                    return 'NO'
                B[j]+=1
                B[j+1]+=1
                count+=2
                if isEvens(B):
                    return str(count)
        return '0'