Skip to content

Commit df41f71

Browse files
authored
Merge branch 'main' into feat/DP_problem
2 parents d6c7934 + 92c8692 commit df41f71

File tree

3 files changed

+90
-0
lines changed

3 files changed

+90
-0
lines changed

135. Candy.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
public:
3+
int candy(vector<int>& ratings) {
4+
int n = ratings.size();
5+
vector<int> count(n, 1); // Step 1: Initialize with 1
6+
7+
// Step 2: Left to Right
8+
for (int i = 1; i < n; i++) {
9+
if (ratings[i] > ratings[i - 1]) {
10+
count[i] = count[i - 1] + 1;
11+
}
12+
}
13+
14+
// Step 3: Right to Left
15+
for (int i = n - 2; i >= 0; i--) {
16+
if (ratings[i] > ratings[i + 1]) {
17+
count[i] = max(count[i], count[i + 1] + 1);
18+
}
19+
}
20+
21+
// Step 4: Total candies
22+
return accumulate(count.begin(), count.end(), 0);
23+
}
24+
};
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <iostream>
2+
using namespace std;
3+
/*
4+
APPROACH:
5+
Use an array to track lengths of increasing streaks, then apply binary search
6+
to find the largest k for which two adjacent increasing subarrays exist.
7+
*/
8+
bool check(int *inc, int n, int k)
9+
{
10+
for (int end1 = k - 1; end1 + k < n; end1++)
11+
{
12+
if (inc[end1] >= k && inc[end1 + k] >= k)
13+
{
14+
return true;
15+
}
16+
}
17+
return false;
18+
}
19+
20+
int maxIncreasingSubarrays(int *nums, int numsSize)
21+
{
22+
int n = numsSize;
23+
int inc[n];
24+
for (int i = 0; i < n; i++)
25+
inc[i] = 1;
26+
27+
// Build the increasing streak lengths
28+
for (int i = 1; i < n; i++)
29+
{
30+
if (nums[i] > nums[i - 1])
31+
{
32+
inc[i] = inc[i - 1] + 1;
33+
}
34+
}
35+
36+
int L = 1, R = n / 2;
37+
int ans = 0;
38+
39+
// Binary search for max k
40+
while (L <= R)
41+
{
42+
int mid = L + (R - L) / 2;
43+
if (check(inc, n, mid))
44+
{
45+
ans = mid; // mid works, try bigger k
46+
L = mid + 1;
47+
}
48+
else
49+
{
50+
R = mid - 1; // mid too big, try smaller k
51+
}
52+
}
53+
54+
return ans;
55+
}

96. Unique Binary Search Trees.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Solution {
2+
public:
3+
int dp[20]{};
4+
int numTrees(int n) {
5+
if(n <= 1) return 1;
6+
if(dp[n]) return dp[n];
7+
for(int i = 1; i <= n; i++)
8+
dp[n] += numTrees(i-1) * numTrees(n-i);
9+
return dp[n];
10+
}
11+
};

0 commit comments

Comments
 (0)