Sub array that produces a given sum and product

后端 未结 4 1575
执念已碎
执念已碎 2021-01-14 13:48

Given an array of length N. How will you find the minimum length contiguous sub-array of whose sum is S and whose product is P. For eg 5 6 1 4 6 2 9 7 fo

4条回答
  •  攒了一身酷
    2021-01-14 14:08

    Just go from left to right, and sum all the numbers, if the sum > S, then throw away left ones.

    import java.util.Arrays;
    
    public class test {
        public static void main (String[] args) {
            int[] array = {5, 6, 1, 4, 6, 2, 9, 7};
            int length = array.length;
            int S = 17;
            int sum = 0;                       // current sum of sub array, assume all positive
            int start = 0;                     // current start of sub array
            int minLength = array.length + 1;  // length of minimum sub array found
            int minStart = 0;                  // start of of minimum sub array found
            for (int index = 0; index < length; index++) {
              sum = sum + array[index];
              // Find by add to right
              if (sum == S && index - start + 1 < minLength) {
                  minLength = index - start + 1;
                  minStart = start;
              }
              while (sum >= S) {
                sum = sum - array[start];
                start++;
                // Find by minus from left
                if (sum == S && index - start + 1 < minLength) {
                    minLength = index - start + 1;
                    minStart = start;
                }
              }
            }
            // Found
            if (minLength != length + 1) {
                System.out.println(Arrays.toString(Arrays.copyOfRange(array, minStart, minStart + minLength)));
            }
        }
    }
    

    For your example, I think it is OR.

    Product is nothing different from sum, except for calculation.

提交回复
热议问题