Sunday, April 26, 2015

Maximum slice problem - MaxSliceSum

Here is another codility problem solution from the codility lessons (MaxSliceSum - Find a maximum sum of a compact subsequence of array elements. ) due to the copy rights I can't copy the content of the problem here so to view the problem description click here.

Please be aware that the following code scores 92% only failed in on test case so if you could find where is the bug I will be glade to tell me.



class Solution {
	public int solution(int[] A) {
		// write your code in Java SE 8
		int sum = 0;
		int maxPosSeries = Integer.MIN_VALUE;
		int sumPos = 0;
		int maxVal = Integer.MIN_VALUE;
		boolean isPosFound = false;
		boolean containsPos = false;
		for (int i = 0; i < A.length; i++) {
			sum += A[i];
			maxVal = Math.max(maxVal, A[i]);
			if (A[i] >= 0) {
				isPosFound = true;
				containsPos = true;
				sumPos += A[i];
				maxPosSeries = Math.max(sumPos, maxPosSeries);

			} else if (A[i] < 0) {
				sumPos = 0;
				isPosFound = false;
			}


		}
		int min = Integer.MAX_VALUE;
		int ans = 0;
		int commulativeSUm = 0;

		for (int i = 0; i < A.length; i++) {
			commulativeSUm += A[i];
			int def = sum - (commulativeSUm);
			if (def < min) {
				min = def;
				ans = commulativeSUm;
			}

		}
		if (!containsPos) return maxVal;
		return Math.max(ans, maxPosSeries);

	}
}

No comments:

Post a Comment