// Cpp program for stock span problem (brute force) #include <iostream> #include <vector> using namespace std; vector<int> calculateSpan(const vector<int>& prices) { int n = prices.size(); vector<int> span(n, 1); for (int i = 0; i < n; ++i) { int spanValue = 1; //traverse backwards and count the number of consecutive days for (int j = i - 1; j >= 0 && prices[j] <= prices[i]; --j) { spanValue++; } span[i] = spanValue; } return span; } int main() { vector<int> stockPrices = {100, 80, 60, 70, 60, 75, 85}; vector<int> span = calculateSpan(stockPrices); cout << "Stock Prices: "; for (int price : stockPrices) { cout << price << " "; } std::cout << "\nSpans: "; for (int s : span) { std::cout << s << " "; } return 0; }
// Java program for stock span problem - brute force approach import java.util.Arrays; public class StockSpan { public static void main(String[] args) { int[] prices = {100, 80, 60, 70, 60, 75, 85}; int[] span = calculateSpan(prices); System.out.println("Stock Prices: " + Arrays.toString(prices)); System.out.println("Spans: " + Arrays.toString(span)); } public static int[] calculateSpan(int[] prices) { int n = prices.length; int[] span = new int[n]; Arrays.fill(span, 1); for (int i = 0; i < n; ++i) { int spanValue = 1; //traverse backwards and count the number of consecutive days for (int j = i - 1; j >= 0 && prices[j] <= prices[i]; --j) { spanValue++; } span[i] = spanValue; } return span; } }
# Python program to solve stock span problem def calculate_span(prices): n = len(prices) span = [1] * n for i in range(1, n): span_value = 1 for j in range(i - 1, -1, -1): if prices[j] > prices[i]: break span_value += 1 span[i] = span_value return span stock_prices = [100, 80, 60, 70, 60, 75, 85] span = calculate_span(stock_prices) print("Stock Prices: " + str(stock_prices)) print("Spans: " + str(span))
// C# code to solve stock span problem - brute force using System; class StockSpan { public static void Main() { int[] prices = {100, 80, 60, 70, 60, 75, 85}; int[] span = CalculateSpan(prices); Console.WriteLine("Stock Prices: " + string.Join(" ", prices)); Console.WriteLine("Spans: " + string.Join(" ", span)); } public static int[] CalculateSpan(int[] prices) { int n = prices.Length; int[] span = new int[n]; Array.Fill(span, 1); for (int i = 0; i < n; ++i) { int spanValue = 1; for (int j = i - 1; j >= 0 && prices[j] <= prices[i]; --j) { spanValue++; } span[i] = spanValue; } return span; } }









Trends is an amazing magazine Blogger theme that is easy to customize and change to fit your needs.