Untitled
unknown
plain_text
a year ago
1.4 kB
4
Indexable
#include <bits/stdc++.h>
using namespace std;
int find_max_elements(vector<int> array) {
if (array.size() < 2) return 0; // Handle cases with insufficient input
int target = array[0]; // The first element is the target
vector<int> nums(array.begin() + 1, array.end()); // Remaining elements are the numbers
// Handle edge case where no elements or target is non-positive
if (nums.empty() || target <= 0) return 0;
// DP map to store the maximum elements count for a specific sum
unordered_map<int, int> dp;
dp[0] = 0; // Base case: 0 elements to achieve sum 0
// Iterate over each number in nums
for (int num : nums) {
unordered_map<int, int> new_dp = dp; // Create a copy of current dp to update
for (const auto& [sum, count] : dp) {
if (sum + num <= target) {
new_dp[sum + num] = max(new_dp[sum + num], count + 1);
}
}
dp = move(new_dp); // Update dp with the newly calculated values
}
// Return the maximum number of elements for the exact target sum
return dp.find(target) != dp.end() ? dp[target] : 0;
}
int main() {
int n, target;
cin >> n >> target;
vector<int> array(n);
array[0] = target; // Include the target as the first element for find_max_elements function
for (int i = 1; i < n; ++i) {
cin >> array[i];
}
cout << find_max_elements(array) << endl;
return 0;
}Editor is loading...
Leave a Comment