Beats 100% Time Complexity | Java | Arithmetic Solution |
Intuition\n Describe your first thoughts on how to solve this problem. \nThe Intuition here is that we need to find how many times we need to use limit to get t
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe Intuition here is that we need to find how many times we need to use limit to get to the difference of current array sum and the goal.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Calculate the array sum.\n- Get the absolute difference between sum and goal - we take absolute because sum can be bigger or smaller than goal, if sum is smaller then we need to add and if it\'s greater then we need to subtract to reach goal but regardless we will subtract or add limit to sum.\n- Divide difference of sum and goal with limit to get the number of times we need to use limit.\n- If diff is exactly divisible by limit then that\'s the answer else add 1 to the answer.\n\nPlease **UPVOTE** if you find helpfull.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n    public int minElements(int[] nums, int limit, int goal) {\n        int n = nums.length;\n        int res = 0;\n        long sum = 0;\n        long lim = (long) limit;\n        long goall = (long) goal;\n        for(int i=0; i<n; i++) sum += nums[i];\n        // System.out.println(sum);\n        long diff = Math.abs(sum-goall);\n        return diff%limit == 0L? (int)(diff/limit) : (int)(diff/limit)+1;\n    }\n}\n```
['Java']