
Sponsored
Sponsored
The dynamic programming approach uses a dp array where dp[i] is true if there is a valid partition for the subarray nums[0..i]. We initialize dp[0] as false because there cannot be a valid partition for a single element. Then, for each i, we check for all valid configurations of subarrays ending at i, i.e., [i-1,i], [i-2,i], and [i-2,i-1,i], updating the dp array accordingly.
Time Complexity: O(n), where n is the length of the array since we iterate through the array once.
Space Complexity: O(n) for the dp array.
1public class Solution {
2 public boolean validPartition(int[] nums) {
3 int n = nums.length;
4 boolean[] dp = new boolean[n + 1];
5 dp[0] = true;
6 dp[1] = nums[0] == nums[1];
7
8 for (int i = 2; i < n; ++i) {
9 if (nums[i] == nums[i - 1] && dp[i - 1]) dp[i + 1] = true;
10 if (nums[i] == nums[i - 1] && nums[i] == nums[i - 2] && dp[i - 2]) dp[i + 1] = true;
11 if (nums[i] - 1 == nums[i - 1] && nums[i - 1] - 1 == nums[i - 2] && dp[i - 2]) dp[i + 1] = true;
12 }
13 return dp[n];
14 }
15}
16This Java solution mirrors the logic applied in Python and C++, and manages partition checks using an array.
The greedy approach attempts to form valid subarrays by traversing the array and greedily picking the largest valid partition at each position. While processing the elements, if a valid subarray is found, the elements involved are ignored in subsequent iterations. Note, this provides a simple but possibly non-optimal solution for certain edge cases.
Time Complexity: O(n)
Space Complexity: O(1)
1publicThis is a Java implementation of the greedy approach to find valid partitions.