具有唯一总和且总和最多为 K 的子数组的计数
给定一个大小为N的数组arr[]和一个整数K .,任务是计算总和最多为K的子数组的数量。
例子:
Input: N = 3, arr[] = {1, 0, 1}, K = 1
Output: 3
Explanation: All Subarrays are [1], [0], [1], [1, 0], [0, 1], [1, 0, 1] & The sum of these subarrays are {1, 0, 1, 1, 1, 2} respectively. There are only 2 distinct possible sums less than or equal to 1
Input: N = 1, arr[] = {1}, K = 0
Output: 0
方法:该任务可以通过计算每个子数组的总和并将它们存储在HashMap中来解决。遍历HashMap并增加计数,如果总和最多为K
下面是上述方法的实现
C++14
// C++ program for the above approach
#include
using namespace std;
// Function to calculate the valid sums
void solve(int arr[], int n, int k)
{
// Store the distinct subarray sums
unordered_map occ;
int cur = 0;
for (int i = 0; i < n; i++) {
cur = 0;
for (int j = i; j < n; j++) {
cur += arr[j];
occ[cur]++;
}
}
// Stores the answer
int ans = 0;
for (auto x : occ) {
if (x.first <= k)
ans++;
}
cout << ans << endl;
}
// Driver Code
int main()
{
int N = 3, K = 1;
int arr[3] = { 1, 0, 1 };
solve(arr, N, K);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to calculate the valid sums
static void solve(int arr[], int n, int k)
{
// Store the distinct subarray sums
HashMap occ = new HashMap();
int cur = 0;
for (int i = 0; i < n; i++) {
cur = 0;
for (int j = i; j < n; j++) {
cur += arr[j];
if(occ.containsKey(cur)){
occ.put(cur, occ.get(cur)+1);
}
else{
occ.put(cur, 1);
}
}
}
// Stores the answer
int ans = 0;
for (Map.Entry x : occ.entrySet()) {
if (x.getKey() <= k)
ans++;
}
System.out.print(ans +"\n");
}
// Driver Code
public static void main(String[] args)
{
int N = 3, K = 1;
int arr[] = { 1, 0, 1 };
solve(arr, N, K);
}
}
// This code is contributed by 29AjayKumar
Python3
# python program for the above approach
# Function to calculate the valid sums
def solve(arr, n, k):
# Store the distinct subarray sums
occ = {}
cur = 0
for i in range(0, n):
cur = 0
for j in range(i, n):
cur += arr[j]
if cur in occ:
occ[cur] += 1
else:
occ[cur] = 1
# Stores the answer
ans = 0
for x in occ:
if (x <= k):
ans += 1
print(ans)
# Driver Code
if __name__ == "__main__":
N = 3
K = 1
arr = [1, 0, 1]
solve(arr, N, K)
# This code is contributed by rakeshsahni
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to calculate the valid sums
static void solve(int[] arr, int n, int k)
{
// Store the distinct subarray sums
Dictionary occ
= new Dictionary();
int cur = 0;
for (int i = 0; i < n; i++) {
cur = 0;
for (int j = i; j < n; j++) {
cur += arr[j];
if (!occ.ContainsKey(cur))
occ[cur] = 0;
else
occ[cur]++;
}
}
// Stores the answer
int ans = 0;
foreach(KeyValuePair x in occ)
{
if (x.Key <= k)
ans++;
}
Console.WriteLine(ans);
}
// Driver Code
public static void Main()
{
int N = 3, K = 1;
int[] arr = { 1, 0, 1 };
solve(arr, N, K);
}
}
// This code is contributed by ukasp.
Javascript
输出
2
时间复杂度:O(N 2 )
辅助空间:O(N)