Sort by

recency

|

754 Discussions

|

  • + 0 comments

    Here is problem solution in python, java, c++, c and javascript programming - https://programmingoneonone.com/hackerrank-fair-rations-problem-solution.html

  • + 0 comments

    This code will timeout

    public static string fairRations(List B) { int count=0;
    bool found=false;

        do{ 
    
            found=false;
    
            if(B.Count < 2 || (B.Count == 2 && (B[0]%2 != B[1]%2)))
            {
                break;
            }
    
            for(int i=0; i<B.Count; i++)
            {
                if(B[i]%2 != 0)
                {
                    found=true;
    
                    B[i]+=1;
    
                    if(i+1 < B.Count)
                    {
                        B[i+1]+=1;
                    }
                    else if(i-1 >=0)
                    {
                        B[i-1]+=1;
                    }
    
                    count+=2;
    
                    break;
                }                
            }
    
        }while(found);
    
        return count>0?count.ToString():"NO";
    }
    

    }

  • + 0 comments

    include

    include

    include

    using namespace std;

    string fairRations(vector B) { int loaves = 0; int n = B.size();

    for (int i = 0; i < n - 1; ++i) {
        if (B[i] % 2 != 0) {
            B[i]++;
            B[i + 1]++;
            loaves += 2;
        }
    }
    
    if (B[n - 1] % 2 != 0) {
        return "NO";
    } else {
        return to_string(loaves);
    }
    

    }

    int main() { ios::sync_with_stdio(false); cin.tie(NULL);

    int n; cin >> n;
    vector<int> B(n);
    for (int i = 0; i < n; ++i) cin >> B[i];
    
    cout << fairRations(B) << "\n";
    
    return 0;
    

    }

  • + 0 comments

    Solution in go

    func fairRations(B []int32) string {
        oddIndex := -1
        totalBreads := int32(0)
        
        for i := 0; i < len(B); i++ {
            if B[i]%2 > 0 {
                if oddIndex < 0 {
                    oddIndex = i
                    continue
                }
                
                totalBreads += int32((i - oddIndex) * 2)
                oddIndex = -1
            }
        }
        if oddIndex >= 0 {
            return "NO"
        }
        
        return fmt.Sprintf("%d", totalBreads)
    }
    
  • + 0 comments

    My Rust solution: -

    fn is_odd(number: &i32) -> bool {
        number % 2 != 0
    }
    
    
    fn fairRations(B: &[i32]) -> String {
        let mut b_vec = B.to_vec();
        let mut counter = 0;
        for i in 0..(b_vec.len() - 1) {
            if is_odd(&b_vec[i]) {
                b_vec[i + 1] += 1;
                counter += 2;
            }
        }
        
        if b_vec.last().unwrap() % 2 == 0 && b_vec.len() > 2 {
            return counter.to_string() 
        }
        return "NO".to_string()
    }