Similar Problems

Similar Problems not available

Longest Square Streak In An Array - Leetcode Solution

Companies:

LeetCode:  Longest Square Streak In An Array Leetcode Solution

Difficulty: Medium

Topics: hash-table dynamic-programming binary-search array sorting  

Problem Description:

Given an array of integers nums representing the raw exam scores of students, return the maximum points you can get by choosing exactly k consecutive scores such that they are all the same.

Solution:

Approach:

We will use the sliding window technique to solve this problem. We will scan the array from the left and keep a sliding window of size = k.

  • We will initialize a variable called maxLength and set it to 0. This variable will keep track of the maximum length of the streak that we can find.
  • We will initialize a variable called currentLength and set it to 1. This variable will keep track of the length of the current streak.
  • We will initialize a variable called currentNum and set it to the first element of the array. This variable will keep track of the current number that we are looking at.
  • We will then loop through the array starting at the second element. For each element in the array:
  • If the current element is equal to the currentNum, then we increment the currentLength variable.
  • If the current element is not equal to the currentNum, then we set the currentNum variable to the current element, and we set the currentLength variable to 1.
  • If the currentLength is greater than or equal to k, then we update the maxLength variable. We also decrement the currentLength variable by 1, because we want to continue the streak without including the current element.
  • Finally, we return the maxLength variable.

Algorithm:

  • Declare a maxLength variable, set it to 0
  • Declare a currentLength variable, set it to 1
  • Declare a currentNum variable, set it to the first element of the array
  • Loop through the array starting at the second element:
    • If the current element is equal to the currentNum, increment currentLength
    • If the current element is not equal to the currentNum, set currentNum to current element and set currentLength to 1
    • If currentLength is greater than or equal to k, update maxLength and decrement currentLength
  • Return maxLength

Code:

class Solution {
public:
    int maxPoints(vector<int>& nums, int k) {
        int maxLength = 0;
        int currentLength = 1;
        int currentNum = nums[0];
        for(int i = 1; i < nums.size(); i++) {
            if(nums[i] == currentNum) {
                currentLength++;
            } else {
                currentNum = nums[i];
                currentLength = 1;
            }
            if(currentLength >= k) {
                maxLength = max(maxLength, k);
                currentLength--;
            }
        }
        return maxLength * k;
    }
};

Longest Square Streak In An Array Solution Code

1