Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views20 pages

Interview C++ Solutions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views20 pages

Interview C++ Solutions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Interview C++ solutions

Here are the C++ solutions for each of the listed array and matrix problems, structured in an interview-
style progression — from brute-force to optimal, where applicable.

✅ 1. Find the First Repeating Element in an Array


🔸 Brute-Force (O(n²))
cpp

int firstRepeatingBrute(vector<int>& arr) {


for (int i = 0; i < arr.size(); i++) {
for (int j = i + 1; j < arr.size(); j++) {
if (arr[i] == arr[j])
return arr[i];
}
}
return -1;
}

🔹 Optimal - HashMap (O(n))


cpp

int firstRepeatingOptimal(vector<int>& arr) {


unordered_map<int, int> indexMap;
int minIndex = INT_MAX;

for (int i = 0; i < arr.size(); i++) {


if (indexMap.count(arr[i])) {
minIndex = min(minIndex, indexMap[arr[i]]);
} else {
indexMap[arr[i]] = i;
}
}

return minIndex == INT_MAX ? -1 : arr[minIndex];


}

✅ 2. Search in Row-wise and Column-wise Sorted Matrix


🔹 Optimal (Start from top-right) — O(m + n)
cpp

bool searchMatrix(vector<vector<int>>& matrix, int target) {


int row = 0, col = matrix[0].size() - 1;

while (row < matrix.size() && col >= 0) {


if (matrix[row][col] == target)
return true;
else if (matrix[row][col] > target)
col--;
else
row++;

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/20
}

return false;
}

✅ 3. Build Max and Min Heap from 14 Integers (Array Representation)


🔹 Max Heap (Using make_heap)

cpp

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void buildMaxHeap(vector<int>& arr) {


make_heap(arr.begin(), arr.end());
}

void buildMinHeap(vector<int>& arr) {


make_heap(arr.begin(), arr.end(), greater<int>());
}

📝 Note: For pictorial representation, you just draw the binary tree based on array indices:
left = 2*i + 1, right = 2*i + 2, parent = (i - 1)/2

✅ 4. Two Sum - Check if Any Two Elements Sum to Target


🔸 Brute-Force — O(n²)
cpp

bool twoSumBrute(vector<int>& nums, int target) {


for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
if (nums[i] + nums[j] == target)
return true;
}
}
return false;
}

🔹 Optimal - HashMap — O(n)


cpp

bool twoSumOptimal(vector<int>& nums, int target) {


unordered_set<int> seen;

for (int num : nums) {


if (seen.count(target - num))
return true;
seen.insert(num);
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/20
return false;
}

🔸 Variation: Two-Pointer (Sorted Array)


cpp

bool twoSumSorted(vector<int>& nums, int target) {


sort(nums.begin(), nums.end());
int left = 0, right = nums.size() - 1;

while (left < right) {


int sum = nums[left] + nums[right];
if (sum == target)
return true;
else if (sum < target)
left++;
else
right--;
}
return false;
}

✅ 5. Search in Rotated Sorted Array


🔹 Optimal - Modified Binary Search — O(log n)
cpp

int searchRotated(vector<int>& nums, int target) {


int low = 0, high = nums.size() - 1;

while (low <= high) {


int mid = low + (high - low) / 2;

if (nums[mid] == target)
return mid;

if (nums[low] <= nums[mid]) {


if (nums[low] <= target && target < nums[mid])
high = mid - 1;
else
low = mid + 1;
} else {
if (nums[mid] < target && target <= nums[high])
low = mid + 1;
else
high = mid - 1;
}
}

return -1;
}

Would you like dry runs or sample test cases added for any of these? I can also format this into a single
PDF or Markdown doc for revision.

Here's a complete interview-style breakdown of the String Manipulation Problems you mentioned,
with C++ implementations for each — starting from brute-force to optimal, where applicable. Each
solution is kept clean, concise, and LeetCode-style.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/20
✅ 1. Reverse a String
🔸 Approach 1: Two Pointers
cpp

void reverseString(vector<char>& s) {
int left = 0, right = s.size() - 1;
while (left < right) {
swap(s[left++], s[right--]);
}
}

🔸 Approach 2: Recursion
cpp

void helper(vector<char>& s, int left, int right) {


if (left >= right) return;
swap(s[left], s[right]);
helper(s, left + 1, right - 1);
}

void reverseString(vector<char>& s) {
helper(s, 0, s.size() - 1);
}

🔸 Approach 3: Built-in reverse


cpp

void reverseString(vector<char>& s) {
reverse(s.begin(), s.end());
}

✅ 2. Reverse Words in a String


🔹 Optimal (Split + Reverse + Join)
cpp

string reverseWords(string s) {
istringstream iss(s);
vector<string> words;
string word;

while (iss >> word)


words.push_back(word);

reverse(words.begin(), words.end());
return accumulate(next(words.begin()), words.end(), words[0],

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/20
[](string a, string b) { return a + " " + b; });
}

✅ 3. Edit Distance (Convert one string to another)


🔹 Optimal – Dynamic Programming (O(m * n))
cpp

int minDistance(string word1, string word2) {


int m = word1.length(), n = word2.length();
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));

for (int i = 0; i <= m; i++)


dp[i][0] = i;
for (int j = 0; j <= n; j++)
dp[0][j] = j;

for (int i = 1; i <= m; i++) {


for (int j = 1; j <= n; j++) {
if (word1[i - 1] == word2[j - 1])
dp[i][j] = dp[i - 1][j - 1];
else
dp[i][j] = 1 + min({dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]});
}
}

return dp[m][n];
}

✅ 4. Check if a String is a Palindrome


🔸 Brute: Create a reversed copy
cpp

bool isPalindrome(string s) {
string rev = s;
reverse(rev.begin(), rev.end());
return s == rev;
}

🔹 Optimal: Two Pointer


cpp

bool isPalindrome(string s) {
int left = 0, right = s.length() - 1;

while (left < right) {


if (s[left++] != s[right--])
return false;
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/20
return true;
}

🔹 Variation: Ignore non-alphanumeric and case


cpp

bool isPalindrome(string s) {
int left = 0, right = s.length() - 1;

while (left < right) {


while (left < right && !isalnum(s[left])) left++;
while (left < right && !isalnum(s[right])) right--;

if (tolower(s[left]) != tolower(s[right]))
return false;

left++, right--;
}
return true;
}

✅ 5. Find Anagrams in List of Strings


🔸 Brute: Check each pair (O(n² * m log m))
cpp

bool isAnagram(string s, string t) {


sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}

🔹 Optimal: Use frequency map (O(n * m))


cpp

vector<vector<string>> groupAnagrams(vector<string>& strs) {


unordered_map<string, vector<string>> mp;

for (string& s : strs) {


string key = s;
sort(key.begin(), key.end()); // Sorted version as key
mp[key].push_back(s);
}

vector<vector<string>> res;
for (auto& [k, v] : mp)
res.push_back(v);

return res;
}

✅ 6. Print Name in Alphabetical Order


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/20
🔹 Simple Sort
cpp

string sortName(string name) {


sort(name.begin(), name.end());
return name;
}

Would you like me to combine this with the previous Arrays & Matrix problems into a printable format
(e.g., PDF or Markdown) for interview prep?

Here are the C++ implementations for the most commonly asked Linked List interview problems,
structured from brute to optimal, where applicable — all in LeetCode-style with clean, reusable code
and edge-case handling.

✅ 1. Insert Element in Sorted Linked List


🔹 Optimal – One pass traversal
cpp

ListNode* insertInSortedList(ListNode* head, int val) {


ListNode* newNode = new ListNode(val);

if (!head || val < head->val) {


newNode->next = head;
return newNode;
}

ListNode* curr = head;


while (curr->next && curr->next->val < val) {
curr = curr->next;
}

newNode->next = curr->next;
curr->next = newNode;

return head;
}

✅ 2. Remove Duplicates from Sorted Linked List


🔹 Optimal – One pass (O(n))
cpp

ListNode* deleteDuplicates(ListNode* head) {


ListNode* curr = head;

while (curr && curr->next) {


if (curr->val == curr->next->val)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/20
curr->next = curr->next->next;
else
curr = curr->next;
}

return head;
}

✅ 3. Detect and Remove Loop in Linked List


🔹 Step 1: Detect cycle using Floyd’s algorithm
cpp

bool hasCycle(ListNode *head) {


ListNode *slow = head, *fast = head;

while (fast && fast->next) {


slow = slow->next;
fast = fast->next->next;

if (slow == fast) return true;


}
return false;
}

🔹 Step 2: Remove loop and find loop start


cpp

void removeLoop(ListNode* head) {


ListNode *slow = head, *fast = head;

// Detect loop
do {
if (!fast || !fast->next) return;
slow = slow->next;
fast = fast->next->next;
} while (slow != fast);

// Find start of loop


slow = head;
if (slow == fast) {
while (fast->next != slow)
fast = fast->next;
} else {
while (slow->next != fast->next) {
slow = slow->next;
fast = fast->next;
}
}

// Remove loop
fast->next = nullptr;
}

✅ 4. Find Middle Element in One Pass (Even with Millions of


Nodes)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/20
🔹 Optimal – Slow and Fast Pointer (O(n), O(1) space)
cpp

ListNode* findMiddle(ListNode* head) {


ListNode* slow = head;
ListNode* fast = head;

while (fast && fast->next) {


slow = slow->next;
fast = fast->next->next;
}

return slow;
}

✅ 5. Merge Two Sorted Linked Lists


🔹 Iterative – Dummy Node (O(n + m))
cpp

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {


ListNode dummy(0);
ListNode* tail = &dummy;

while (l1 && l2) {


if (l1->val < l2->val) {
tail->next = l1;
l1 = l1->next;
} else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}

tail->next = l1 ? l1 : l2;

return dummy.next;
}

🔹 Recursive Merge (Alternative)


cpp

ListNode* mergeTwoListsRecursive(ListNode* l1, ListNode* l2) {


if (!l1) return l2;
if (!l2) return l1;

if (l1->val < l2->val) {


l1->next = mergeTwoListsRecursive(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoListsRecursive(l1, l2->next);
return l2;
}
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/20
Would you like to combine this along with:

Arrays & Matrix Problems ✅


String Problems ✅
And output all into one printable PDF or Markdown interview sheet?

Here are the C++ implementations for essential Tree Data Structure Problems, structured in an
interview-style format — with concise code, explained strategies, and variations when applicable.

✅ 1. Root-to-Leaf Path Sum Equals Given Number


🔹 DFS with Backtracking
cpp

bool hasPathSum(TreeNode* root, int targetSum) {


if (!root) return false;

if (!root->left && !root->right)


return targetSum == root->val;

return hasPathSum(root->left, targetSum - root->val) ||


hasPathSum(root->right, targetSum - root->val);
}

🔸 Follow-up: Find All Such Paths


cpp

void dfs(TreeNode* root, int sum, vector<int>& path, vector<vector<int>>& res) {


if (!root) return;

path.push_back(root->val);
if (!root->left && !root->right && sum == root->val)
res.push_back(path);
else {
dfs(root->left, sum - root->val, path, res);
dfs(root->right, sum - root->val, path, res);
}
path.pop_back();
}

vector<vector<int>> pathSum(TreeNode* root, int targetSum) {


vector<vector<int>> res;
vector<int> path;
dfs(root, targetSum, path, res);
return res;
}

✅ 2. Boundary Traversal of Binary Tree


🔹 Full Implementation
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/20
cpp

bool isLeaf(TreeNode* node) {


return !node->left && !node->right;
}

void addLeft(TreeNode* root, vector<int>& res) {


TreeNode* curr = root->left;
while (curr) {
if (!isLeaf(curr)) res.push_back(curr->val);
curr = curr->left ? curr->left : curr->right;
}
}

void addLeaves(TreeNode* root, vector<int>& res) {


if (isLeaf(root)) {
res.push_back(root->val);
return;
}
if (root->left) addLeaves(root->left, res);
if (root->right) addLeaves(root->right, res);
}

void addRight(TreeNode* root, vector<int>& res) {


TreeNode* curr = root->right;
stack<int> stk;
while (curr) {
if (!isLeaf(curr)) stk.push(curr->val);
curr = curr->right ? curr->right : curr->left;
}
while (!stk.empty()) {
res.push_back(stk.top());
stk.pop();
}
}

vector<int> boundaryTraversal(TreeNode* root) {


if (!root) return {};
if (isLeaf(root)) return {root->val};

vector<int> res = {root->val};


addLeft(root, res);
addLeaves(root, res);
addRight(root, res);

return res;
}

✅ 3. AVL Tree – Self-Balancing Tree


🔹 AVL Tree Node & Rotations
cpp

struct TreeNode {
int val, height;
TreeNode *left, *right;
TreeNode(int x) : val(x), height(1), left(nullptr), right(nullptr) {}
};

int height(TreeNode* node) {


return node ? node->height : 0;
}

int getBalance(TreeNode* node) {


return height(node->left) - height(node->right);

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/20
}

TreeNode* rotateRight(TreeNode* y) {
TreeNode* x = y->left;
TreeNode* T2 = x->right;

x->right = y;
y->left = T2;

y->height = 1 + max(height(y->left), height(y->right));


x->height = 1 + max(height(x->left), height(x->right));

return x;
}

TreeNode* rotateLeft(TreeNode* x) {
TreeNode* y = x->right;
TreeNode* T2 = y->left;

y->left = x;
x->right = T2;

x->height = 1 + max(height(x->left), height(x->right));


y->height = 1 + max(height(y->left), height(y->right));

return y;
}

🔹 Insert with Balancing


cpp

TreeNode* insertAVL(TreeNode* node, int key) {


if (!node) return new TreeNode(key);

if (key < node->val) node->left = insertAVL(node->left, key);


else if (key > node->val) node->right = insertAVL(node->right, key);
else return node;

node->height = 1 + max(height(node->left), height(node->right));


int balance = getBalance(node);

// Left Left
if (balance > 1 && key < node->left->val)
return rotateRight(node);

// Right Right
if (balance < -1 && key > node->right->val)
return rotateLeft(node);

// Left Right
if (balance > 1 && key > node->left->val) {
node->left = rotateLeft(node->left);
return rotateRight(node);
}

// Right Left
if (balance < -1 && key < node->right->val) {
node->right = rotateRight(node->right);
return rotateLeft(node);
}

return node;
}

✅ 4. Binary Search Tree (Insert, Delete, Search, Inorder)


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/20
🔹 Insert
cpp

TreeNode* insertBST(TreeNode* root, int val) {


if (!root) return new TreeNode(val);
if (val < root->val) root->left = insertBST(root->left, val);
else root->right = insertBST(root->right, val);
return root;
}

🔹 Search
cpp

bool searchBST(TreeNode* root, int key) {


if (!root) return false;
if (root->val == key) return true;
return key < root->val ? searchBST(root->left, key) : searchBST(root->right, key);
}

🔹 Inorder Traversal
cpp

void inorder(TreeNode* root) {


if (!root) return;
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}

🔹 Delete Node
cpp

TreeNode* findMin(TreeNode* node) {


while (node && node->left) node = node->left;
return node;
}

TreeNode* deleteNode(TreeNode* root, int key) {


if (!root) return nullptr;

if (key < root->val)


root->left = deleteNode(root->left, key);
else if (key > root->val)
root->right = deleteNode(root->right, key);
else {
if (!root->left) return root->right;
else if (!root->right) return root->left;

TreeNode* temp = findMin(root->right);


root->val = temp->val;
root->right = deleteNode(root->right, temp->val);
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/20
return root;
}

✅ 5. Insert Element in Complete Binary Tree


🔸 Approach 1: Array Representation (Heap Style)
cpp

// Complete Binary Tree insertion is implicit in array-based representation


vector<int> tree;

void insert(int val) {


tree.push_back(val); // push at end; parent = (i-1)/2
}

🔸 Approach 2: Level-Order (Queue-Based)


cpp

TreeNode* insertCBT(TreeNode* root, int val) {


if (!root) return new TreeNode(val);
queue<TreeNode*> q;
q.push(root);

while (!q.empty()) {
TreeNode* curr = q.front(); q.pop();
if (!curr->left) {
curr->left = new TreeNode(val);
break;
} else q.push(curr->left);

if (!curr->right) {
curr->right = new TreeNode(val);
break;
} else q.push(curr->right);
}

return root;
}

Would you like this Tree section combined with:

Arrays + Matrix ✅
Strings ✅
Linked List ✅
into a printable Markdown or PDF sheet for placement revision?

Here are the C++ implementations for key Sorting and Searching problems, structured interview-style
— from brute-force (if relevant) to optimal solutions, with clean explanations and code.

✅ 1. Merge Sort (Stable O(n log n) Sorting Algorithm)


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/20
🔹 Optimal – Merge Sort
cpp

void merge(vector<int>& arr, int l, int m, int r) {


int n1 = m - l + 1;
int n2 = r - m;

vector<int> L(n1), R(n2);


for (int i = 0; i < n1; i++) L[i] = arr[l + i];
for (int j = 0; j < n2; j++) R[j] = arr[m + 1 + j];

int i = 0, j = 0, k = l;
while (i < n1 && j < n2)
arr[k++] = (L[i] <= R[j]) ? L[i++] : R[j++];

while (i < n1) arr[k++] = L[i++];


while (j < n2) arr[k++] = R[j++];
}

void mergeSort(vector<int>& arr, int l, int r) {


if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}

🧠 Why Merge Sort?


Time Complexity: O(n log n) in all cases

Space Complexity: O(n) — because of temporary arrays


Stable sort

🔸 Follow-up: Space Optimization


Merge Sort can be done in-place but it's complex and not used in interviews. The default
recursive method above is expected in interviews. Alternatively, use Iterative Merge Sort to
reduce stack usage.

✅ 2. Sort an Array of 0s, 1s, and 2s (Dutch National Flag Problem)


🔹 Optimal – Three Pointer / Dutch National Flag (O(n), O(1))
cpp

void sortColors(vector<int>& nums) {


int low = 0, mid = 0, high = nums.size() - 1;

while (mid <= high) {


if (nums[mid] == 0) {
swap(nums[low++], nums[mid++]);
} else if (nums[mid] == 1) {
mid++;
} else {

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/20
swap(nums[mid], nums[high--]);
}
}
}

🧠 Key Idea: Keep all 0s before low, all 2s after high, and 1s in the middle.

✅ 3. Binary Search Implementation


🔹 Standard Binary Search – Sorted Array
cpp

int binarySearch(vector<int>& arr, int target) {


int low = 0, high = arr.size() - 1;

while (low <= high) {


int mid = low + (high - low) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}

🔹 Search in Rotated Sorted Array (LeetCode 33)


cpp

int searchRotated(vector<int>& nums, int target) {


int low = 0, high = nums.size() - 1;

while (low <= high) {


int mid = (low + high) / 2;

if (nums[mid] == target) return mid;

// Left sorted
if (nums[low] <= nums[mid]) {
if (nums[low] <= target && target < nums[mid])
high = mid - 1;
else
low = mid + 1;
}
// Right sorted
else {
if (nums[mid] < target && target <= nums[high])
low = mid + 1;
else
high = mid - 1;
}
}

return -1;
}

✅ 4. Find First and Last Occurrence of Target


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/20
🔹 Modified Binary Search – Two Passes
🔸 First Occurrence
cpp

int firstOccurrence(vector<int>& nums, int target) {


int low = 0, high = nums.size() - 1, res = -1;

while (low <= high) {


int mid = (low + high) / 2;

if (nums[mid] == target) {
res = mid;
high = mid - 1; // search left
} else if (nums[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return res;
}

🔸 Last Occurrence
cpp

int lastOccurrence(vector<int>& nums, int target) {


int low = 0, high = nums.size() - 1, res = -1;

while (low <= high) {


int mid = (low + high) / 2;

if (nums[mid] == target) {
res = mid;
low = mid + 1; // search right
} else if (nums[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return res;
}

Would you like me to:

📂 Combine this Sorting + Searching section with the previously covered:


Arrays + Matrices ✅

Strings ✅
Linked Lists ✅
Trees ✅

📄 Format them into a PDF or Markdown "Placement Prep Handbook"?


Here are the most asked Dynamic Programming problems with clean, structured C++
implementations — following an interview-style progression from optimal base approaches to follow-

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/20
up optimizations and variations.

✅ 1. 0-1 Knapsack Problem


🔹 Standard DP – 2D Table (O(n × W))
cpp

int knapsack(vector<int>& weights, vector<int>& values, int n, int W) {


vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0));

for (int i = 1; i <= n; i++) {


for (int w = 0; w <= W; w++) {
if (weights[i - 1] <= w)
dp[i][w] = max(values[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w]);
else
dp[i][w] = dp[i - 1][w];
}
}
return dp[n][W];
}

🔸 Follow-up: Space Optimized DP – 1D Array (O(n × W), O(W))


cpp

int knapsackOptimized(vector<int>& weights, vector<int>& values, int n, int W) {


vector<int> dp(W + 1, 0);

for (int i = 0; i < n; i++) {


for (int w = W; w >= weights[i]; w--) {
dp[w] = max(dp[w], values[i] + dp[w - weights[i]]);
}
}
return dp[W];
}

✅ 2. Largest Sum Contiguous Subarray (Kadane’s Algorithm)


🔹 Optimal – Kadane's Algorithm (O(n))
cpp

int maxSubArray(vector<int>& nums) {


int currSum = nums[0], maxSum = nums[0];

for (int i = 1; i < nums.size(); i++) {


currSum = max(nums[i], currSum + nums[i]);
maxSum = max(maxSum, currSum);
}

return maxSum;
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/20
🧠 Handles all negatives: Works because it compares nums[i] individually.

🔸 Variation: Return the Subarray as well


cpp

pair<int, pair<int, int>> maxSubArrayIndices(vector<int>& nums) {


int currSum = nums[0], maxSum = nums[0], start = 0, end = 0, tempStart = 0;

for (int i = 1; i < nums.size(); i++) {


if (nums[i] > currSum + nums[i]) {
currSum = nums[i];
tempStart = i;
} else {
currSum += nums[i];
}

if (currSum > maxSum) {


maxSum = currSum;
start = tempStart;
end = i;
}
}

return {maxSum, {start, end}};


}

✅ 3. Maximum Profit from Stock Prices


🔹 Variation 1: Single Transaction (Buy once, sell once)
cpp

int maxProfitSingle(vector<int>& prices) {


int minPrice = INT_MAX, maxProfit = 0;

for (int price : prices) {


minPrice = min(minPrice, price);
maxProfit = max(maxProfit, price - minPrice);
}

return maxProfit;
}

🔹 Variation 2: Unlimited Transactions (Buy & sell multiple times)


cpp

int maxProfitMultiple(vector<int>& prices) {


int profit = 0;
for (int i = 1; i < prices.size(); i++) {
if (prices[i] > prices[i - 1])
profit += prices[i] - prices[i - 1];
}
return profit;
}

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/20
🔹 Variation 3: At Most 2 Transactions (DP)
cpp

int maxProfitTwoTransactions(vector<int>& prices) {


int n = prices.size();
vector<int> left(n, 0), right(n, 0);

int minPrice = prices[0];


for (int i = 1; i < n; i++) {
minPrice = min(minPrice, prices[i]);
left[i] = max(left[i - 1], prices[i] - minPrice);
}

int maxPrice = prices[n - 1];


for (int i = n - 2; i >= 0; i--) {
maxPrice = max(maxPrice, prices[i]);
right[i] = max(right[i + 1], maxPrice - prices[i]);
}

int maxProfit = 0;
for (int i = 0; i < n; i++)
maxProfit = max(maxProfit, left[i] + right[i]);

return maxProfit;
}

Would you like to:

📄 Combine this Dynamic Programming section with:


Arrays, Strings, Linked Lists, Trees, Sorting + Searching ✅
📥 Export everything into a "Complete Placement Preparation PDF / Markdown Doc"?

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/20

You might also like