File tree Expand file tree Collapse file tree 2 files changed +52
-0
lines changed
src/main/java/com/thealgorithms/prefixsum Expand file tree Collapse file tree 2 files changed +52
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments