โ Question 1: Sum of Digits
๐งพ Problem Statement:
Given an array of integers called prices
, return the sum of all elements in the array.
๐ฅ Input: An array of integers.
๐ค Output: A single integer โ the sum of all elements in the array.
Example:
Input: [1, 2, 3]
Output: 6
๐งฉ Approach
First, initialize a variable
sum
with a value of0
.Loop through each element in the array using a
for
loop.In each iteration, add the current element to the
sum
.After the loop ends, return the final value of
sum
.
๐ป Code:
var SumOfDigits = function(prices) {
let sum = 0;
for (let i = 0; i < prices.length; i++) {
sum += prices[i];
}
return sum;
};
console.log(SumOfDigits([1, 2, 3])); // Output: 6
๐งช Edge Cases:
- โ
Empty
array []
โ Output should be 0 since there are no elements to sum. - โ Array with one element [10] โ Output should be 10.
- โ Array with negative numbers [-1, -2, 3] โ Output should be 0.
Complexity
โฑ๏ธ Time Complexity:
-
O(n)
where n is the number of elements in the array.
๐ฆ Space Complexity:
-
O(1)
โ No extra space used apart from a constant sum variable.
โ Question 2: Best Time to Buy Stock
The goal is to find the maximum profit
from a single buy and sell operation on a stock, where the buy must happen before the sell.
-
To solve this, we:
- Keep track of the minimum price seen so far.
- At each step, calculate the profit if we sell at the current price.
- If this profit is greater than the current maximum profit, we update it.
Example:
Input: [1, 2, 3]
Output: 6
๐งฉ Approach
-
Initialize two variables:
-
min_Price
to store the lowest price so far (starting withprices[0]
) -
max_Profit
to store the highest profit so far (starting at0
)
-
-
Iterate through the
prices
array** starting from index1
:- At each step:
- If
prices[i] - min_Price
(profit) is greater thanmax_Profit
, updatemax_Profit
- If
prices[i]
is less thanmin_Price
, updatemin_Price
- If
- At each step:
Return
max_Profit
after the loop ends.
This approach ensures that we always buy at the lowest price seen so far and sell at the highest price that comes after, achieving the maximum profit from one transaction.
๐ป Code:
var maxProfit = function(prices) {
let min_Price = prices[0]
let max_Price = 0;
for(let x = 1 ; x < prices.length ; x++){
if(prices[x] - min_Price > max_Price){
max_Price = prices[x] - min_Price
}
if(prices[x] < min_Price){
min_Price = prices[x]
}
}
return max_Price;
};
Complexity
โฑ๏ธ Time Complexity:
O(n)
โ We traverse the prices
array only once, where n
is the length of the array.
๐ฆ Space Complexity:
O(1)
โ We use only a constant amount of extra space (min_Price
and max_Profit
).
Top comments (0)