Monthly Archives: March 2023
C# || Daily Temperatures – How To Find The Number Of Days Until Warmer Temperature Using C#
The following is a module with functions which demonstrates how to find the number of days until warmer temperature using C#.
1. Daily Temperatures – Problem Statement
Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
Example 1:
Input: temperatures = [73,74,75,71,69,72,76,73]
Output: [1,1,4,2,1,1,0,0]
Example 2:
Input: temperatures = [30,40,50,60]
Output: [1,1,1,0]
Example 3:
Input: temperatures = [30,60,90]
Output: [1,1,0]
2. Daily Temperatures – Solution
The following is a solution which demonstrates how to find the number of days until warmer temperature.
This solution uses the monotonic stack approach.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// ============================================================================ // Author: Kenneth Perkins // Date: Mar 1, 2023 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to find number of days until warmer temperature // ============================================================================ public class Solution { public int[] DailyTemperatures(int[] temperatures) { // Stack used to save the array index of each item var stack = new Stack<int>(); var result = new int[temperatures.Length]; // Go through items in the array for (int currentIndex = 0; currentIndex < temperatures.Length; ++currentIndex) { // Compare the item at the top of the stack to the current array item. // If the item at the top of stack is less than current array item, // save the distance between the array indexes in the result array. while (stack.Count > 0 && temperatures[stack.Peek()] < temperatures[currentIndex]) { // Get the distance between the two array indexes var previousIndex = stack.Pop(); result[previousIndex] = currentIndex - previousIndex; } // Save the array index for this item to the stack stack.Push(currentIndex); } return result; } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output for the example cases:
[1,1,4,2,1,1,0,0]
[1,1,1,0]
[1,1,0]