Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static class FenwickTree {
- private long[] tree;
- private int size;
- public FenwickTree(int size) {
- this.size = size;
- tree = new long[size + 1];
- }
- public void update(int idx, long val) {
- while (idx <= size) {
- tree[idx] += val;
- idx += idx & -idx;
- }
- }
- public long query(int idx) {
- long result = 0;
- while (idx > 0) {
- result += tree[idx];
- idx -= idx & -idx;
- }
- return result;
- }
- }
- static class Dividend {
- public long amount = 0;
- public long days = 0;
- public Dividend(long amount, long days) {
- this.amount = amount;
- this.days = days;
- }
- }
- static class FuturePricingEngine {
- private long stockPrice;
- private List<Dividend> dividends;
- private FenwickTree fenwickTree;
- public FuturePricingEngine(long stockPrice, List<Dividend> dividends) {
- this.stockPrice = stockPrice;
- this.dividends = dividends;
- int maxDays = (int) dividends.stream().mapToLong(dividend -> dividend.days).max().orElse(0);
- fenwickTree = new FenwickTree(maxDays);
- for (Dividend dividend : dividends) {
- fenwickTree.update((int) dividend.days, dividend.amount);
- }
- }
- public void updateDividend(int dividendIndex, Dividend updatedDividend) {
- dividendIndex -= 1;
- Dividend oldDividend = dividends.get(dividendIndex);
- fenwickTree.update((int) oldDividend.days, -oldDividend.amount);
- fenwickTree.update((int) updatedDividend.days, updatedDividend.amount);
- dividends.set(dividendIndex, updatedDividend);
- }
- public long calculateFuturePrice(long daysToFuture) {
- long totalDividends = fenwickTree.query((int) daysToFuture);
- return stockPrice - totalDividends;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement