LeetCode 2518: Number of Great Partitions

Problem Description

Explanation:

To solve this problem, we can use dynamic programming. We will iterate through the array and for each element, we will consider two options - whether to include it in the first group or the second group. We will keep track of the sum of elements in each group and the count of great partitions generated so far.

At each step, we will check if the sum of elements in each group is greater than or equal to k. If it is, we will increment the count of great partitions. Finally, we return the count modulo 10^9 + 7 as the result.

Algorithm:

  1. Initialize variables to keep track of the count of great partitions and the sum of elements in each group.
  2. Iterate through the array and at each step, consider two options - include the element in the first group or the second group.
  3. Update the sum of elements in each group accordingly.
  4. If the sum of elements in each group is greater than or equal to k, increment the count of great partitions.
  5. Return the count of great partitions modulo 10^9 + 7.

Time Complexity:

The time complexity of this solution is O(n), where n is the number of elements in the input array.

Space Complexity:

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

:

Solutions

class Solution {
    public int countGreatPartitions(int[] nums, int k) {
        long count = 0;
        long sum1 = 0, sum2 = 0;
        int mod = 1000000007;
        
        for (int num : nums) {
            sum2 += num;
        }
        
        for (int i = 0; i < nums.length - 1; i++) {
            sum1 += nums[i];
            sum2 -= nums[i];
            if (sum1 >= k && sum2 >= k) {
                count = (count + (sum1 - k + 1) * (sum2 - k + 1)) % mod;
            }
        }
        
        return (int) count;
    }
}

Loading editor...