Skip to content

Commit 72cea60

Browse files
#7209 adding prefixsum algorithms by adding two java files prefixsum.java and prefixsum1.java
1 parent 66f76eb commit 72cea60

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.thealgorithms.prefixsum;
2+
3+
class prefixsum {
4+
int[] prefix;
5+
public prefixsum(int[] nums) {
6+
int n = nums.length;
7+
prefix = new int[n];
8+
int cur = 0;
9+
for (int i = 0; i < n; i++) {
10+
cur += nums[i];
11+
prefix[i] = cur;
12+
}
13+
}
14+
public int sumRange(int left, int right) {
15+
if (left == 0) {
16+
return prefix[right];
17+
} else {
18+
return prefix[right] - prefix[left - 1];
19+
}
20+
}
21+
22+
public static void main(String[] args) {
23+
int[] nums = { 1, 2, 3, 4 };
24+
prefixsum obj = new prefixsum(nums);
25+
System.out.println(obj.sumRange(0, 2));
26+
System.out.println(obj.sumRange(1, 3));
27+
}
28+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.thealgorithms.prefixsum;
2+
3+
class Solution {
4+
public int minSubArrayLen(int target, int[] nums) {
5+
int currentsum = 0;
6+
int low = 0;
7+
int high = 0;
8+
9+
int minlenwindow = Integer.MAX_VALUE;
10+
11+
for (high = 0; high < nums.length; high++) {
12+
currentsum += nums[high];
13+
14+
while (currentsum >= target) {
15+
int currentwindow = high - low + 1;
16+
minlenwindow = Math.min(minlenwindow, currentwindow);
17+
currentsum = currentsum - nums[low];
18+
low++;
19+
}
20+
}
21+
22+
return minlenwindow == Integer.MAX_VALUE ? 0 : minlenwindow;
23+
}
24+
}

0 commit comments

Comments
 (0)