Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2561. Rearranging Fruits

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)

:

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);
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.