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 bool ValidPartition(int[] nums) {
3 int n = nums.Length;
4 bool[] dp = new bool[n + 1];
5 dp[0] = true;
6 if (n > 1) 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 - 1] == 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}
16
The C# solution checks possible valid partitions with a similar logical structure in other languages.
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)
1function
This JavaScript solution aims to validate partitions by iterating over the array and selecting valid subarrays optimally.