Day 7 โ Squares of Sorted Array & Best Time to Buy/Sell Stock | Two Pointer + Greedy | LeetCode Challenge


๐๏ธ Date: August 1, 2025
๐ Challenge:
๐งฉ Problem 1: Squares of a Sorted Array โ LeetCode #977 (Easy)
๐งฉ Problem 2: Best Time to Buy and Sell Stock โ LeetCode #121 (Easy)
๐ป Topic: Two Pointer, Greedy, Arrays
โ Problem Statement (Summary):
๐น Problem 1: Squares of a Sorted Array
Goal: Given a sorted array (non-decreasing), return a new array of squares sorted in non-decreasing order.
Example:
Input: nums = [-4, -1, 0, 3, 10]
โ Output: [0, 1, 9, 16, 100]
Explanation: Squared โ [16, 1, 0, 9, 100]
โ Sorted โ [0, 1, 9, 16, 100]
๐ง What I Learned (Problem 1):
Use two pointers (start and end) to compare absolute values.
Square the larger value, insert it at the end of result array (back to front).
Helps handle negatives efficiently without sorting again.
๐งช Code (C++):
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int i = 0, j = nums.size() - 1, idx = nums.size() - 1;
vector<int> result(nums.size());
while (j >= i) {
int i2 = nums[i] * nums[i];
int j2 = nums[j] * nums[j];
if (i2 < j2) {
result[idx] = j2;
j--;
} else {
result[idx] = i2;
i++;
}
idx--;
}
return result;
}
};
๐ Time Complexity: O(n)
๐ฆ Space Complexity: O(n)
๐ธ LeetCode Submission Screenshot:
โ Key Takeaways:
Square and compare from both ends.
Insert larger square from end to start.
Avoid using extra sort for efficiency.
๐น Problem 2: Best Time to Buy and Sell Stock
Goal: Find max profit by choosing one day to buy and one future day to sell.
Example:
Input: prices = [7,1,5,3,6,4]
โ Output: 5
Explanation: Buy at 1, sell at 6 โ profit = 6 - 1 = 5
๐ง What I Learned (Problem 2):
Use greedy approach with two pointers.
Track min price so far using left pointer.
At each step, compute potential profit and store max.
๐งช Code (C++):
class Solution {
public:
int maxProfit(vector<int>& prices) {
int i = 0, j = 1, maxBuy = 0, profit, n = prices.size();
while (j < n) {
if (prices[i] <= prices[j]) {
profit = prices[j] - prices[i];
maxBuy = max(profit, maxBuy);
} else {
i = j;
}
j++;
}
return maxBuy;
}
};
๐ Time Complexity: O(n)
๐ฆ Space Complexity: O(1)
๐ธ LeetCode Submission Screenshot:
โ Key Takeaways:
Buy low (track min so far), sell high (future price).
Shift buy pointer only when a lower price is found.
One-pass greedy is optimal.
๐ Progress Tracker:
โ
Day: 7 / 30
๐งฉ Total Problems Solved: 2
๐งญ Focus Today: Two Pointer + Greedy
๐๏ธ Tags:#leetcode #30DaysChallenge #twopointers #greedy #cpp #dsa #arrays #squaresorted #buysellstock #codingjourney
Subscribe to my newsletter
Read articles from Tanishi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
