Solution 4 for Scaler Topics Fortnightly Contest - 24
Mario's Divisibility Dilemma
This article is part of the Scaler Topics Fortnightly Contest - 24
Build an AI-First Career, Master the Complete Skillset
Choose from our industry-leading programs designed for career success
Modern Software and AI Engineering Program
Master full-stack development with AI integration
+1000 moreModern Data Science and ML with specialisation in AI
Advanced data science techniques with AI specialization
+1000 moreAdvanced AIML with Specialisation in Agentic AI
Deep dive into AIML with focus on Agentic systems
+1000 moreDevOps, Cloud & AI Platform Engineering
Build and manage AI-powered cloud infrastructure
+1000 moreAI Engineering Advanced Certification by IIT-Roorkee
Premier AI engineering certification from IIT-Roorkee
AI Forward Deployed Engineer Program
Full-stack engineering, production AI and client-facing consulting
+1000 moreSolution Approach
-
Let’s consider the scenario where there exists a value ‘k’ that evenly divides the number of chocolates in each box. In this case, ‘k’ must be a divisor of the total sum of chocolates across all boxes.
-
To ensure that the number of chocolates in each box is divisible by ‘k’, we have two options: either the chocolates in each box should be exactly ‘k’, or they should be ‘0’. However, any other multiple of ‘k,’ like 2k or 3k, would necessitate more moves, as you can deduce.
-
To minimize the number of moves required, we would redistribute the chocolates in a way that the first ‘k’ boxes containing 1 chocolate consolidate all these chocolates into the box at their median position. It is straightforward to demonstrate that this is the optimal strategy. This process is repeated (sum / k) times.
-
By applying this strategy, we can systematically evaluate each divisor of the total chocolate sum and calculate the number of moves required to achieve the desired distribution. The divisor that results in the fewest moves will be our answer.
Time Complexity:
Space Complexity:
C++ Implementation
Java Implementation
How Scaler Transformed Careers in Different Fields
Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.