Approach:
- Initialize three pointers:
low
,mid
, andhigh
. - Traverse the array using the
mid
pointer:- If
nums[mid] == 0
: Swap it withnums[low]
, and increment bothlow
andmid
. - If
nums[mid] == 1
: Simply incrementmid
. - If
nums[mid] == 2
: Swap it withnums[high]
, and decrementhigh
.
- If
- Continue until
mid
exceedshigh
.
Approach:
- Initialize two variables:
Count
: for tracking the count of the current candidate.Element
: for the candidate element.
- Traverse through the given array:
- If
Count
is 0, setElement
to the current element. - If the current element is the same as
Element
, increaseCount
by 1. - If they are different, decrease
Count
by 1.
- If
- The integer present in
Element
should be the result we are expecting. ex: https://leetcode.com/problems/majority-element/description/
Kadane's Algorithm is used to find the maximum sum of a contiguous subarray in an array of integers (positive or negative).
- Initialize two variables:
currentSum
: Stores the sum of the current subarray.maxSum
: Tracks the maximum subarray sum found so far.
- Traverse the array:
- Add each element to
currentSum
. - If
currentSum
is less than the current element, resetcurrentSum
to the current element (start a new subarray). - Update
maxSum
ifcurrentSum
is larger thanmaxSum
.
- Add each element to
- Return
maxSum
. ex: https://www.geeksforgeeks.org/batch/gfg-160-problems/track/arrays-gfg-160/problem/kadanes-algorithm-1587115620