-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Sync LeetCode submission - Buy Two Chocolates (javascript)
- Loading branch information
1 parent
00d4ade
commit 80d0ca1
Showing
1 changed file
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
/** | ||
* @param {number[]} prices | ||
* @param {number} money | ||
* @return {number} | ||
*/ | ||
var buyChoco = function(prices, money) { | ||
// Initialize variables to store the two minimum costs | ||
// As the constraints are 1 <= money <= 100, set initial minimum costs to a value greater than 100 | ||
let firstMinCost = 101, secondMinCost = 101; | ||
|
||
// Iterate through the array of chocolate prices | ||
for (let p of prices) { | ||
// Check if the current price is smaller than the first minimum cost | ||
if (p < firstMinCost) { | ||
// If yes, update the second minimum cost and set the first minimum cost to the current price | ||
secondMinCost = firstMinCost; | ||
firstMinCost = p; | ||
} else { | ||
// If the current price is greater than or equal to the first minimum cost, | ||
// update the second minimum cost if the current price is smaller than the second minimum cost | ||
secondMinCost = Math.min(secondMinCost, p); | ||
} | ||
} | ||
|
||
// Calculate the leftover money after buying the two cheapest chocolates | ||
let leftover = money - (firstMinCost + secondMinCost); | ||
|
||
// Return the non-negative leftover money, or the original money if all available money is spent | ||
return leftover >= 0 ? leftover : money; | ||
}; |