arrays - Finding the maximum elements (consecutive) whose sum is less than a given value? -


so, have array of positive natural numbers. given threshold value. have find out, maximum count of numbers (consecutive) sum less given threshold value.

for example,  ip: arr = {3,1,2,1} threshold = 5  o/p: 3 

maximum size of input array can 10^5.

basically, thought of algorithm calculates count of elements in subsets of original array sum less given threshold. but, lead complexity of o(n^2). can suggest better algorithm? not looking code , algorithm/pseudocode fine. thanks!

public static int maximumsum(int[] array, int t){     int maxsum = 0;     int cursum = 0;     int start = 0;     int end = 0;     while(start < array.length){          if(cursum > maxsum && cursum <= t){             maxsum = cursum;         }         if(cursum <= t && end < array.length){             cursum += array[end];             end += 1;          }         else{             cursum -= array[start];             start+= 1;         }     }     return maxsum; } 

the complexity of code o(2 * n) o(n). can't think of improvement this.


Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

php - Find a regex to take part of Email -