LeetCode 2561: Rearranging Fruits Solution

Master LeetCode problem 2561 (Rearranging Fruits), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2561. Rearranging Fruits

Problem Explanation

Explanation:

To solve this problem, we can iterate over all possible combinations of swapping two fruits between the baskets and find the minimum cost required to make them equal. We need to keep track of the minimum cost achieved so far. If it is not possible to make the baskets equal, we return -1.

  1. Iterate over each pair of indices i and j.
  2. Swap the fruits at indices i and j between the baskets.
  3. Calculate the cost of the swap as the minimum between the fruits at indices i and j.
  4. Update the baskets after the swap.
  5. Check if the baskets are equal after sorting them.
  6. If they are equal, update the minimum cost achieved so far.
  7. Finally, return the minimum cost or -1 if it's impossible to make the baskets equal.

Time Complexity: O(n^2) where n is the number of fruits in each basket. Space Complexity: O(1)

:

Solution Code

class Solution {
    public int minimumCost(int[] basket1, int[] basket2) {
        int n = basket1.length;
        int minCost = Integer.MAX_VALUE;
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                int swapCost = Math.min(basket1[i], basket2[j]);
                int temp1 = basket1[i];
                int temp2 = basket2[j];
                
                basket1[i] = temp2;
                basket2[j] = temp1;
                
                if (isSortedEqual(basket1, basket2)) {
                    minCost = Math.min(minCost, swapCost);
                }
                
                basket1[i] = temp1;
                basket2[j] = temp2;
            }
        }
        
        return minCost == Integer.MAX_VALUE ? -1 : minCost;
    }
    
    private boolean isSortedEqual(int[] arr1, int[] arr2) {
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        return Arrays.equals(arr1, arr2);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2561 (Rearranging Fruits)?

This page provides optimized solutions for LeetCode problem 2561 (Rearranging Fruits) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2561 (Rearranging Fruits)?

The time complexity for LeetCode 2561 (Rearranging Fruits) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2561 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2561 in Java, C++, or Python.

Back to LeetCode Solutions