Vikasa M R’s Post

View profile for Vikasa M R, graphic

Dynamic Backend Developer | Expertise in Java, Spring Boot, Cloud Engineering & Microservices | Proven Success in Performance Optimization & Scalable Solutions | Passionate About Innovation & Team Collaboration

Day 12 of Solving LeetCode 75 [ q- 14 ] Maximum Average Subarray I You are given an integer array nums consisting of n elements, and an integer k. Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10^-5 will be accepted. Example 1: Input: nums = [1,12,-5,-6,50,3], k = 4 Output: 12.75000 Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75 Example 2: Input: nums = [5], k = 1 Output: 5.00000 Constraints: n == nums.length 1 <= k <= n <= 105 -104 <= nums[i] <= 104 In a java class 1. Create a method which accepts an array of numbers and a integer variable k. 2. Initialize a long variable to store the sum of k integers. 3. Use a for loop to find the sum of first k elements. 4. Initialize a variable to store the maximum sum. 5. Iterate through the array starting from index k. 6. Update the sum by adding the current element and subtracting the element at position (i - k). 7. Update the maximum sum. 8. Calculate and return the maximum average by dividing the maximum sum by k. Time Complexity: The code iterates through the array nums only once, both iterations have a time complexity of O(n), where n is the length of the array nums, therefore, the overall time complexity is O(n). Space Complexity: The code uses a constant amount of extra space regardless of the input size, therefore, the space complexity is O(1), constant space complexity. #java #leetcode

To view or add a comment, sign in

Explore topics