forked from joharbatta/DataStructure-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubArraySumLessK.java
More file actions
70 lines (63 loc) · 1.61 KB
/
subArraySumLessK.java
File metadata and controls
70 lines (63 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.Scanner;
public class subArraySumLessK {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i =0; i < n;i++){
arr[i] = sc.nextInt();
}
int k = sc.nextInt();
countSubArray(n,arr,k);
}
static void countSubArray(int n,int arr[],int k)
{
int start=0;
int end=0;
int sum=arr[0];
int count=0;
while(end<n && start<n)
{
if(sum<k)
{
end++;
count+=end-start;
if(end<n)
{
sum+=arr[end];
}
}
else{
sum-=arr[start];
start++;
}
}
if(count>=0)
System.out.println(count);
else
System.out.println("0");
}
// static void countSubArray(int n, int[] arr,int k){
// // Write your code here
// int c=0;
// int max=Integer.MIN_VALUE;
// for(int i=0;i<n;i++)
// {
// for(int j=i;j<n;j++)
// {
// int sum=0;
// for(int d=i;d<=j;d++)
// {
// sum+=arr[d];
// }
// //System.out.print(sum+" ");
// if(sum<k)
// {
// c++;
// //System.out.println(sum);
// }
// }
// }
// System.out.print(c);
// }
}