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

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;




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值