#include <iostream>
#include <unordered_map>
#include <vector>
std::vector<int> largestSubarrayWithZeroSum(std::vector<int> &nums) {
std::unordered_map<int, int> hashMap;
std::vector<int> result;
int maxLength = 0, sum = 0, endIndex = -1;
for (int i = 0; i < nums.size(); ++i) {
sum += nums[i];
if (nums[i] == 0 && maxLength == 0) {
maxLength = 1;
endIndex = i;
}
if (sum == 0) {
maxLength = i + 1;
endIndex = i;
}
if (hashMap.find(sum) != hashMap.end()) {
if (i - hashMap[sum] > maxLength) {
maxLength = i - hashMap[sum];
endIndex = i;
}
} else {
hashMap[sum] = i;
}
}
if (maxLength) {
for (int i = endIndex - maxLength + 1; i <= endIndex; ++i) {
result.push_back(nums[i]);
}
}
return result;
}
int main() {
std::vector<int> arr = {15, -2, 2, -8, 1, 7, 10, 23};
std::vector<int> result = largestSubarrayWithZeroSum(arr);
if (!result.empty()) {
std::cout << "The largest subarray with zero sum is: ";
for (int num : result) {
std::cout << num << " ";
}
std::cout << std::endl;
} else {
std::cout << "No subarray with zero sum found." << std::endl;
}
return 0;
}