Subarray range with given sum | GFG POTD 15 Oct 2024 | JAVA | C++

preview_player
Показать описание
#gfgpotd #gfgproblemoftheday #gfgtoday
#gfgpotd #gfgproblemoftheday #gfgtoday #gfgpotdtoday #potd #potdgfg #potdgfgtoday #gfgstreek #problemoftheday
Рекомендации по теме
Комментарии
Автор

C++ Code :
int subArraySum(const std::vector<int>& arr, int tar) {
// Using an unordered_map (similar to HashMap in Java)
std::unordered_map<int, int> map;
map[0] = 1; // This is equivalent to map.put(0, 1) in Java

int sum = 0;
int ans = 0;

for (int ele : arr) {
sum += ele;
map[sum]++;

if (map.find(sum - tar) != map.end()) {
ans += map[sum - tar];
}
}

return ans;
}

ajinkyajain
Автор

JAVA Code :
static int subArraySum(int arr[], int tar) {
// add your code here
int sum = 0;
int ans = 0;
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
for(int ele : arr){
sum += ele;
map.put(sum, map.getOrDefault(sum, 0) + 1);
if(map.containsKey(sum - tar)){
ans += map.get(sum - tar);
}
}
return ans;
}

ajinkyajain