Sort by

recency

|

748 Discussions

|

  • + 0 comments

    JAVA

    public static String fairRations(List B) { // Write your code here

    int count = 0;
    for(int i=0;i<B.size();i++){
        int num = B.get(i);
        if(B.get(i)%2!=0){
            B.set(i,num+1);
            count++;
            if(i==B.size()-1){
                B.set(i-1,B.get(i-1)+1);
                count++;
            }else{
                B.set(i+1,B.get(i+1)+1);
                count++;
            }
        }
    }
    boolean flag = true;
    for(int i=0;i<B.size();i++){
        if(B.get(i)%2!=0){
            flag = false;
            break;
        }
    }
    String result = ""+count;
    if(flag==true){
        return result;
    }else{
        return "NO";
    }
    
    }
    
  • + 0 comments
    def fairRations(B):
        # Write your code here
        c = 0
        n = len(B)
        for i in range(n - 1):
            if B[i] % 2 != 0:
                B[i + 1] += 1
                c += 2
                
        return "NO" if B[-1] % 2 != 0 else str(c)
    
  • + 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