现在的位置: 首页 > 综合 > 正文

数组面试题之子数组(subarray)

2014年12月06日 ⁄ 综合 ⁄ 共 1249字 ⁄ 字号 评论关闭

1. QUESTION: Given an array, subarray size k and a number ssum, find the number of subarrays of size k that sum up to ssum.

ANSWER:

1) sum the first k element from array. 
2) Start a loop from k+1 element to end. 
3) inside the loop, add current element to the current sum and subtract (current ptr - k)th value from the sum. 
4) Whenever sum is equal to ssum, keep that as result.


2. QUESTION:  n numbers (both +ve and -ve) are arranged in a circle. find the maximum sum of consecutive nos. Do this in O(n) time

E.g.: {8,-8,9,-9,10,-11,12}max = 22 (12 + 8 - 8 + 9 - 9 + 10)

Answer: Use  Modified Kadane's Algorithm

import java.util.Arrays;

public class MaxSumSequence {
	public static void search(int[] a) {
		int maxStart=0, maxEnd=0, maxSum=0, start=-1, sum=0;
		for(int i=0; i<2*a.length-1; i++) {
			if(start==-1) {
				start = i;
			}
			sum = sum + a[i%a.length];
			if(sum<=0) {
				sum = 0;
				start = -1;
			} else if(sum>maxSum) {
				maxStart = start;
				maxEnd = i;
				maxSum = sum;
			}
		}
		System.out.print("{");
		for(int i=maxStart; i<=maxEnd; i++) {
			if(i!=maxStart) {
				System.out.print(",");
			}
			System.out.print(a[i%a.length]);
		}
		System.out.println("}");
	}

	public static void main(String[] args) {
		int[] a = {8,-8,9,-9,10,-11,12 };
		System.out.println(Arrays.toString(a));
		search(a);
	}
}


3. QUESTION: Given a array, find out if there exist a subarray such its sum is zero.

answer:

subarray=>contiguous slice
take cumulative sum of the array; if the cumulative sum has duplicate numbers then there is subarray which sums to zero;


抱歉!评论已关闭.