Skip to content

Commit e977e94

Browse files
authored
solution(cpp,java): Problems 1425 and 238
238. Product of Array Except Self - C++ 1425. Constrained Subsequence Sum - C++ - Java
2 parents 276ef49 + 5c7bce1 commit e977e94

File tree

5 files changed

+158
-0
lines changed

5 files changed

+158
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <deque>
4+
#include <algorithm>
5+
using namespace std;
6+
7+
class Solution
8+
{
9+
public:
10+
int constrainedSubsetSum(vector<int> &nums, int k)
11+
{
12+
vector<int> dp(nums);
13+
deque<int> q;
14+
q.push_back(0);
15+
for (int i = 1; i < nums.size(); i++)
16+
{
17+
while (!q.empty() && q.back() < i - k)
18+
{
19+
q.pop_back();
20+
}
21+
dp[i] = max(dp[i], dp[q.back()] + nums[i]);
22+
while (!q.empty() && dp[q.front()] <= dp[i])
23+
{
24+
q.pop_front();
25+
}
26+
q.push_front(i);
27+
}
28+
return *max_element(dp.begin(), dp.end());
29+
}
30+
};
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import java.util.Arrays;
2+
3+
public class sol {
4+
public static void main(String[] args) {
5+
// call the fn here
6+
}
7+
class Solution {
8+
public int constrainedSubsetSum(int[] nums, int k) {
9+
int[] dp = Arrays.copyOf(nums, nums.length);
10+
Deque<Integer> q = new ArrayDeque<>();
11+
q.offerLast(0);
12+
for (int i = 1; i < nums.length; i++) {
13+
while (!q.isEmpty() && q.peekLast() < i - k) {
14+
q.pollLast();
15+
}
16+
dp[i] = Math.max(dp[i], dp[q.peekLast()] + nums[i]);
17+
while (!q.isEmpty() && dp[q.peekFirst()] <= dp[i]) {
18+
q.pollFirst();
19+
}
20+
q.offerFirst(i);
21+
}
22+
int max = Integer.MIN_VALUE;
23+
for (int num : dp) {
24+
max = Math.max(max, num);
25+
}
26+
return max;
27+
}
28+
}
29+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
## Approach: Dynamic Programming with Deque
2+
3+
### Intuition
4+
5+
To find the maximum sum of a non-empty subsequence, we can use dynamic programming (DP). We define `dp[i]` as the maximum sum of a non-empty subsequence of `nums[:i+1]`. The result we seek is the maximum value in the `dp` array. Initially, we can compute `dp[i]` using the recurrence `dp[i] = nums[i] + max(dp[i-k], dp[i-k+1], ..., dp[i-1])`. However, this approach would be too slow and result in a Time Limit Exceeded (TLE) error. To optimize it, we use a deque data structure to keep track of the maximum value within a sliding window.
6+
7+
### Algorithm
8+
9+
1. Initialize a deque `q` to store indices.
10+
2. Create a `dp` array with the same length as `nums` and initialize it with the values of `nums`.
11+
3. Iterate through the `nums` array from left to right (index `i` from 1 to `nums.size()`):
12+
- While the deque `q` is not empty and the index at the back of `q` is out of the window of size `k`, pop the back element from `q`.
13+
- While the deque is not empty and the `dp` value at the front index of `q` is smaller than `dp[i]`, pop the front element from `q`.
14+
- Append the current `dp[i]` value to the deque `q`.
15+
- Update `dp[i]` by taking the maximum between its current value and `dp[q[0]] + nums[i]`. This step captures the idea of maximizing the subsequence sum while adhering to the constraint.
16+
4. After the loop, the result is the maximum value in the `dp` array, which can be found using the `max_element` function.
17+
5. Return the result as the answer.
18+
19+
### Complexity
20+
21+
- Time complexity: O(N) where N is the length of the `nums` array.
22+
- Space complexity: O(K), where K is the constraint that limits the size of the deque.
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#include <iostream>
2+
#include <vector>
3+
4+
using namespace std;
5+
6+
class Solution
7+
{
8+
public:
9+
vector<int> productExceptSelf(vector<int> &nums)
10+
{
11+
vector<int> answer;
12+
int m = 1;
13+
int m1 = 1;
14+
int count = 0;
15+
for (int i = 0; i < nums.size(); i++)
16+
{
17+
answer.push_back(nums[i]);
18+
if (nums[i] != 0)
19+
{
20+
m = m * nums[i];
21+
m1 = m1 * nums[i];
22+
}
23+
else
24+
{
25+
m = m * nums[i];
26+
count++;
27+
}
28+
}
29+
for (int i = 0; i < nums.size(); i++)
30+
{
31+
if (count > 1)
32+
{
33+
answer[i] = 0;
34+
}
35+
else if (nums[i] == 0)
36+
{
37+
answer[i] = m1;
38+
}
39+
else
40+
answer[i] = m / nums[i];
41+
}
42+
return answer;
43+
}
44+
};
45+
46+
int main()
47+
{
48+
49+
// call the fn here
50+
return 0;
51+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
## Solution
2+
3+
The provided solution is implemented in C++ and uses two passes through the `nums` array to calculate the `answer` vector without using division.
4+
5+
1. **Initialization**:
6+
- Initialize an empty vector `answer`.
7+
- Initialize two variables `m` and `m1` to 1, which will be used to track the product of non-zero elements and all elements, respectively.
8+
- Initialize a variable `count` to keep track of the number of zeros in the array.
9+
10+
2. **First Pass**:
11+
- Iterate through the `nums` array.
12+
- For each element `nums[i]`, add it to the `answer` vector.
13+
- Update `m` and `m1` by multiplying them with the current element `nums[i]`.
14+
- If the current element is 0, increment the `count` variable.
15+
16+
3. **Second Pass**:
17+
- Iterate through the `nums` array again.
18+
- For each element at index `i`, calculate the value for `answer[i]` based on the following conditions:
19+
- If `count` is greater than 1 (meaning there are more than one zero in the array), set `answer[i]` to 0 because the product of all elements would be 0.
20+
- If `nums[i]` is 0, set `answer[i]` to `m1`. This is because the product of all elements except the zero element is equal to `m1`.
21+
- Otherwise, set `answer[i]` to the result of dividing `m` by `nums[i`, which effectively gives the product of all elements except the current one.
22+
23+
4. **Return**:
24+
- Return the `answer` vector, which contains the desired result.
25+
26+
The provided solution correctly handles different cases and satisfies the O(n) time complexity constraint, but it uses O(n) extra space to store the `answer` vector. Achieving O(1) extra space complexity would require a different approach, such as using prefix and suffix products with careful computation.

0 commit comments

Comments
 (0)