From 60d4dadcac1349e16ee3e1dce0e5f4bbff533fb2 Mon Sep 17 00:00:00 2001 From: DawitGG <124334081+DawitGG@users.noreply.github.com> Date: Sat, 11 Feb 2023 07:57:42 +0300 Subject: [PATCH] Update isMadhavArray.java --- Solutions/isMadhavArray.java | 74 +++++++++++++----------------------- 1 file changed, 26 insertions(+), 48 deletions(-) diff --git a/Solutions/isMadhavArray.java b/Solutions/isMadhavArray.java index 38fb933..c853070 100644 --- a/Solutions/isMadhavArray.java +++ b/Solutions/isMadhavArray.java @@ -17,52 +17,30 @@ public static void main(String[] args){ } static int isMadhavArray(int[] a){ - int isMadhavArray = 0; - int arrayLength = a.length; - int startIndex = 0; // start index of current array elements under consideration - int endIndex = 0; // end index of current array elements under consideration - int n = 1; // track current length of array elements between start and end index - int currentSum = 0; // current sum of array elements - int sum = 0; // sum of elements of array between startIndex and endIndex - int currentLengthOfArray = 1; // length of array from index 0 to endIndex - int calculatedLengthOfArray = 1; // length calculating n * (n+1)/2 - while(currentLengthOfArray <= arrayLength){ - if(currentLengthOfArray == calculatedLengthOfArray){ - for(int index = startIndex; index <= endIndex; index++){ - sum += a[index]; - } - }else{ - // Fail ::: The length of a Madhav array must be n*(n+1)/2 for some n - isMadhavArray = 0; - break; - } - if((currentSum == sum) || (startIndex == endIndex)){ // startIndex == endIndex to satisfy initial condition - currentSum = sum; - sum = 0; - isMadhavArray = 1; - }else{ - // Fail ::: The sum is not equal - isMadhavArray = 0; - break; - } - if(currentLengthOfArray == arrayLength){ - // already at the end of the array - break; - }else{ - startIndex = endIndex + 1; - endIndex = startIndex + n; - if((startIndex < arrayLength && endIndex < arrayLength)){ - // operating inside the array bounderies - n++; - }else{ - // adjusting boundries; so that lastIndex points last element of array - endIndex = arrayLength - 1; - n = endIndex - startIndex; - } - calculatedLengthOfArray = n * (n + 1)/2; - currentLengthOfArray = endIndex + 1; - } - } - return isMadhavArray; + boolean flag = false; + for (int i = 1; i <= a.length; i++) { + if (a.length == i * (i + 1) / 2) + flag = true; + } + + if (!flag) + return 0; + + for (int i = 1; i < a.length; i++) { + int sum = 0; + int x = i * (i + 1) / 2; + + if (x >= a.length) { + break; + } + + for (int j = x; j <= (x + i); j++) { + sum += a[j]; + } + + if (a[0] != sum) + return 0; + } + return 1; } -} \ No newline at end of file +}