Answer to Question #254880 in Java | JSP | JSF for Dharmveer Singh

Question #254880

1. Suppose you have been working with an organization called 'Money Traders' for the past few years. The organization is into the money trading business. Your manager assigned you a task. For a given array of stock's prices for N days, find the stock's span for each day.


The span of the stock's price today is defined as the maximum number of consecutive days(starting from today and going backwards) for which the price of the stock was less than today's price.


For example, if the price of a stock over a period of 7 days are [100, 80, 60, 70, 60, 75, 85], then the stock spans will be [1, 1, 1, 2, 1, 4, 6].


Explanation:


On the sixth day when the price of the stock was 75, the span came out to be 4, because the last prices (including the current price of 75) were less than the current or the sixth day's price.


Similarly, we can deduce the remaining results.


You have to return an array of spans corresponding to each day's stock's price.




1
Expert's answer
2021-10-21T16:03:34-0400


package spanstock;


public class SpanStock {


    static void spanningStock(int arr[], int len, int answer[])
    {
      
        answer[0] = 1;
 
        
        for (int i = 1; i < len; i++) {
            int count = 1;
            while ((i - count) >= 0 && arr[i] >= arr[i - count]) {
                count += answer[i - count];
            }
            answer[i] = count;
        }
    }
 
   
    static void display(int a[], int x)
    {
        for (int i = 0; i < x; i++)
            System.out.print(a[i] + " ");
    }
 
    
    public static void main(String[] args)
    {
        int stock_price[] = { 100, 80, 60, 70, 60, 75, 85};
        int len = stock_price.length;
        int a[] = new int[len];
 
        
        spanningStock(stock_price, len, a);
 
       
        display(a, len);
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS