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.

1445. Apples & Oranges

Database

Explanation

To solve this problem, we need to find the maximum number of apples and oranges that can be collected while maintaining a balance between them. We can achieve this by iterating through the given arrays of apples and oranges, and for each position, we calculate the total weight of apples and oranges on both sides of that position. We then update the count of apples and oranges collected based on the balance condition.

Algorithmic Steps:

  1. Iterate through the given arrays of apples and oranges.
  2. At each position, calculate the total weight of apples and oranges on both sides of that position.
  3. Update the count of apples and oranges collected based on the balance condition.
  4. Return the maximum count of apples and oranges that can be collected.

Time Complexity

The time complexity of this solution is O(n), where n is the total number of elements in the arrays of apples and oranges.

Space Complexity

The space complexity of this solution is O(1) as we are using a constant amount of extra space.

class Solution {
    public int maxApplesOranges(int[] apples, int[] oranges) {
        int leftApples = 0, rightApples = 0;
        int leftOranges = 0, rightOranges = 0;
        
        int maxApples = 0, maxOranges = 0;
        
        for (int i = 0; i < apples.length; i++) {
            rightApples += apples[i];
        }
        
        for (int i = 0; i < oranges.length; i++) {
            rightOranges += oranges[i];
        }
        
        for (int i = 0; i < apples.length; i++) {
            leftApples += apples[i];
            rightApples -= apples[i];
            
            leftOranges += oranges[i];
            rightOranges -= oranges[i];
            
            maxApples = Math.max(maxApples, Math.min(leftApples, rightOranges));
            maxOranges = Math.max(maxOranges, Math.min(leftOranges, rightApples));
        }
        
        return Math.max(maxApples, maxOranges);
    }
}

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.