64

Replace a nested O(n²) loop with two indices that move through the array in O(n).

Two pointers C++ 10 lines
// sorted array: is there a pair with sum = target?
bool pairSum(vector<int> &a, int target) {
    int i = 0, j = a.size() - 1;
    while (i < j) {
        int s = a[i] + a[j];
        if (s == target) return true;
        if (s < target) i++; else j--;
    }
    return false;
}
Sliding window C++ 11 lines
// maximum sum of any k consecutive elements
int maxWindow(vector<int> &a, int k) {
    int sum = 0;
    for (int i = 0; i < k; i++) sum += a[i];
    int best = sum;
    for (int i = k; i < a.size(); i++) {
        sum += a[i] - a[i - k];   // slide: add new, remove old
        best = max(best, sum);
    }
    return best;
}
Kadane's algorithm (maximum subarray) C++ 8 lines
int maxSubArray(vector<int> &a) {
    int cur = a[0], best = a[0];
    for (int i = 1; i < a.size(); i++) {
        cur = max(a[i], cur + a[i]);
        best = max(best, cur);
    }
    return best;   // {-2,1,-3,4,-1,2,1,-5,4} → 6
}