Advertisement
rajeshinternshala

Untitled

Jul 24th, 2023
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.08 KB | None | 0 0
  1.     static class FenwickTree {
  2.         private long[] tree;
  3.         private int size;
  4.  
  5.         public FenwickTree(int size) {
  6.             this.size = size;
  7.             tree = new long[size + 1];
  8.         }
  9.  
  10.         public void update(int idx, long val) {
  11.             while (idx <= size) {
  12.                 tree[idx] += val;
  13.                 idx += idx & -idx;
  14.             }
  15.         }
  16.  
  17.         public long query(int idx) {
  18.             long result = 0;
  19.             while (idx > 0) {
  20.                 result += tree[idx];
  21.                 idx -= idx & -idx;
  22.             }
  23.             return result;
  24.         }
  25.     }
  26.  
  27.     static class Dividend {
  28.         public long amount = 0;
  29.         public long days = 0;
  30.  
  31.         public Dividend(long amount, long days) {
  32.             this.amount = amount;
  33.             this.days = days;
  34.         }
  35.     }
  36.  
  37.     static class FuturePricingEngine {
  38.         private long stockPrice;
  39.         private List<Dividend> dividends;
  40.         private FenwickTree fenwickTree;
  41.  
  42.         public FuturePricingEngine(long stockPrice, List<Dividend> dividends) {
  43.             this.stockPrice = stockPrice;
  44.             this.dividends = dividends;
  45.             int maxDays = (int) dividends.stream().mapToLong(dividend -> dividend.days).max().orElse(0);
  46.             fenwickTree = new FenwickTree(maxDays);
  47.             for (Dividend dividend : dividends) {
  48.                 fenwickTree.update((int) dividend.days, dividend.amount);
  49.             }
  50.         }
  51.  
  52.         public void updateDividend(int dividendIndex, Dividend updatedDividend) {
  53.             dividendIndex -= 1;
  54.             Dividend oldDividend = dividends.get(dividendIndex);
  55.             fenwickTree.update((int) oldDividend.days, -oldDividend.amount);
  56.             fenwickTree.update((int) updatedDividend.days, updatedDividend.amount);
  57.             dividends.set(dividendIndex, updatedDividend);
  58.         }
  59.  
  60.         public long calculateFuturePrice(long daysToFuture) {
  61.             long totalDividends = fenwickTree.query((int) daysToFuture);
  62.             return stockPrice - totalDividends;
  63.         }
  64.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement