|
| 1 | +# Function to calculate the sum |
| 2 | +def calculate_sum(index, mid, n): |
| 3 | + |
| 4 | + # Initialize count |
| 5 | + count = 0 |
| 6 | + |
| 7 | + # Calculate the sume on the left side of the index |
| 8 | + if mid > index: |
| 9 | + count += (mid + mid - index) * (index + 1) // 2 |
| 10 | + else: |
| 11 | + count += (mid + 1) * mid // 2 + index - mid + 1 |
| 12 | + |
| 13 | + # Calculate the sum on the right side of the index |
| 14 | + if mid >= n - index: |
| 15 | + count += (mid + mid - n + 1 + index) * (n - index) // 2 |
| 16 | + else: |
| 17 | + count += (mid + 1) * mid // 2 + n - index - mid |
| 18 | + |
| 19 | + # Subtract the mid at the index |
| 20 | + return count - mid |
| 21 | + |
| 22 | + |
| 23 | + |
| 24 | +def max_value(n, index, max_sum): |
| 25 | + |
| 26 | + # Initialize left and right |
| 27 | + left = 1 |
| 28 | + right = max_sum |
| 29 | + |
| 30 | + # Binary search for the maximum mid at the index |
| 31 | + while left < right: |
| 32 | + |
| 33 | + # Check if current mid is a valid maximum mid |
| 34 | + mid = (left + right + 1) // 2 |
| 35 | + |
| 36 | + # Move to right half if valid |
| 37 | + if calculate_sum(index, mid, n) <= max_sum: |
| 38 | + left = mid |
| 39 | + |
| 40 | + # Otherwise, move to left half |
| 41 | + else: |
| 42 | + right = mid - 1 |
| 43 | + |
| 44 | + # Maximum vlaid mid at index |
| 45 | + return left |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | +# Time Complexity = O(log(maxsum)) |
| 50 | +# Space Complexity = O(1) |
| 51 | + |
| 52 | + |
| 53 | + |
| 54 | +################################################################## |
| 55 | + |
| 56 | + |
| 57 | + |
| 58 | +# Driver code |
| 59 | +def main(): |
| 60 | + input_list = [ |
| 61 | + (6, 3, 18), |
| 62 | + (4, 2, 6), |
| 63 | + (3, 0, 3), |
| 64 | + (5, 3, 15), |
| 65 | + (7, 4, 20)] |
| 66 | + |
| 67 | + for i, (n, index, maxSum) in enumerate(input_list): |
| 68 | + result = max_value(n, index, maxSum) |
| 69 | + print(f"{i + 1}.\tInput: n = {n}, index = {index}, maxSum = {maxSum}") |
| 70 | + print(f"\tMaximum mid at index {index}: {result}") |
| 71 | + print('-' * 100) |
| 72 | + |
| 73 | +if __name__ == "__main__": |
| 74 | + main() |
| 75 | + |
0 commit comments