Posts

Showing posts with the label Contest

Finding the Power of K-Size Subarrays: A Comprehensive Guide

Image
 Understanding the Problem In this LeetCode problem, we're tasked with finding the "power" of all subarrays of size K within a given array of integers. The power of a subarray is defined as: Maximum element if all elements are consecutive and sorted in ascending order. -1 otherwise. Brute Force Approach: A Simple Start A straightforward approach involves iterating over every possible subarray of size K, checking its validity, and calculating its power. Here's Java code for the same: class Solution { public int[] resultsArray(int[] nums, int k) { int n = nums.length; int[] ans = new int[n - k + 1]; for(int i = 0; i <= n-k; i++) { int f = 0; for(int j = i; j < i+k; j++) { // cur element = prev element + 1 if(j > i && nums[j] != nums[j-1] + 1) { f = 1; // Violation of the rule was found bre...

Deriving the Formula for the Sum of an Arithmetic Progression (AP)

Image
Understanding Arithmetic Progression (AP) An arithmetic progression (AP) is a sequence of numbers such that the difference between any two consecutive terms is constant. This constant difference is known as the common difference (d).   For example, the sequence 2, 5, 8, 11, ... is an AP with a common difference of 3. Deriving the Formula Let's consider an AP with the first term a_1 and a common difference d . The nth term of this AP is given by: a_n = a_1 + (n-1)d Now, let's denote the sum of the first n terms of this AP as S_n . We can write S_n as: S_n = a_1 + (a_1 + d) + ... + (a_1 + (n-2)d) + (a_1 + (n-1)d) We can also write S_n in reverse order: S_n = (a_1 + (n-1)d) + (a_1 + (n-2)d) + ... + (a_1 + d) + a_1 Adding these two equations, we get: 2S_n = (2a_1 + (n-1)d) + (2a_1 + (n-1)d ) + ... + (2a_1 + (n-1)d) (n times) Simplifying: 2S_n = n * (2a_1 + (n-1)d) Dividing both sides by 2: S_n = (n/2) * [2a_1 + (n-1)d] This is the formula for the sum of the first n terms of ...