Billboards


Problem Statement :


ADZEN is a popular advertising firm in your city that owns all n billboard locations on Main street. The city council passed a new zoning ordinance mandating that no more than k consecutive billboards may be up at any given time. For example, if there are n=3 billboards on Main street and k=1, ADZEN must remove either the middle billboard, the first two billboards, the last two billboards or the first and last billboard.

Being a for-profit company, ADZEN wants to lose as little advertising revenue as possible when removing the billboards. They want to comply with the new ordinance in such a way that the remaining billboards maximize their total revenues (i.e., the sum of revenues generated by the billboards left standing on Main street).

Given n, k, and the revenue of each of the n billboards, find and print the maximum profit that ADZEN can earn while complying with the zoning ordinance. Assume that Main street is a straight, contiguous block of n billboards that can be removed but cannot be reordered in any way.

For example, if there are n=7 billboards, and k=3 is the maximum number of consecutive billboards that can be active, with revenues = [5,6,4,2,10,8,4], then the maximum revenue that can be generated is 37: 5+6+4+2+10+8+4 = 37.

Function Description

Complete the billboards function in the editor below. It should return an integer that represents the maximum revenue that can be generated under the rules.

billboards has the following parameter(s):

k: an integer that represents the longest contiguous group of billboards allowed
revenue: an integer array where each element represents the revenue potential for a billboard at that index
Input Format

The first line contains two space-separated integers, n (the number of billboards) and k (the maximum number of billboards that can stand together on any part of the road).
Each line i of the n subsequent lines contains an integer denoting the revenue value of billboard i (where 0 <= i < n).

Constraints
1 <= n <= 10^5
1 <= k <= n
0 <= revenue value of any billboard <= 2.10^9

Output Format

Print a single integer denoting the maximum profit ADZEN can earn from Main street after complying with the city's ordinance.



Solution :



title-img


                            Solution in C :

In C++ :







#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;


typedef long long llong;
typedef vector<int> int_v;
typedef vector<llong> llong_v;



llong solve(int n, int k, int_v &vs)
{
  llong_v max_vs(n);
  int_v min_left_len(n);
  
  max_vs[0] = vs[0];
  min_left_len[0] = vs[0] > 0 ? 1 : 0;
  
  for (int i=1 ; i < n ; i++)
    if (min_left_len[i-1] < k)
    {
      max_vs[i] = max_vs[i-1] + vs[i];
      min_left_len[i] = min_left_len[i-1] + 1;    
    }
    else
    {
      llong max_v = max_vs[i-1]; 
      int min_ll = 0;
      
      llong tail = 0;
      for (int j=1 ; j <= k && j <= i+1 ; j++)
      {
        tail += vs[i-j+1];
        llong v = tail;
        if (i-j-1 >= 0)
          v += max_vs[i-j-1];
        if (v > max_v)
        {
          max_v = v;
          min_ll = j;
        }
      }
      
      max_vs[i] = max_v;
      min_left_len[i] = min_ll;
    }
  
  return max_vs[n-1];
}


int main(int, char **)
{
  int n, k;
  cin >> n >> k;
  
  int_v vs(n);
  for (int i=0 ; i < n ; i++)
    cin >> vs[i];

  cout << solve(n, k, vs) << endl;  
}








In Java :





import java.util.Scanner;


public class Solution {

	public static void main (String args[]) {
		Scanner sc = new Scanner(System.in);
		String line=sc.nextLine();
		String[] nk=line.split(" ");
        int n=Integer.parseInt(nk[0]);
        int k=Integer.parseInt(nk[1]);
		long[] p  = new long[n];
        for (int i=0;i<n;i++) {
            line = sc.nextLine();
            p[i] = Long.parseLong(line);
        }
        

        long[] notUse = new long[n];
        long[] best = new long[n];
        notUse[0]=0;
        best[0]=p[0];
        long runningChain=p[0];
        int cL=1;
        for (int i=1;i<n;i++) {
        	notUse[i]=best[i-1];
        	best[i]=best[i-1];
        	if (cL<k) {
        		cL++;
        		runningChain+=p[i];
        		if (i-cL<0) {
        			best[i]=runningChain;
        		} else {
        			best[i]=runningChain+notUse[i-cL];
        		}
        	} else {
        		runningChain+=p[i];
        		//Tricky part
        		int bestCL=0;
        		long bestRunningChain=0;
        		for (int j=i-k;j<i;j++) {
            		runningChain-=p[j];
            		if (runningChain+notUse[j] > best[i]) {
            			best[i]=runningChain+notUse[j];
            			bestCL=i-j;
            			bestRunningChain=runningChain;
            		}
        		}
        		runningChain=bestRunningChain;
        		cL=bestCL;
        	}
        }
        System.out.println(best[n-1]);
	}
	
}








In C :





#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdint.h>

struct moving_min {
  int64_t value;
  int index;
};

struct queue {
  int max_size;
  int first;
  int last;
  int size;
  struct moving_min* values;
};

// Queue functions
struct moving_min* front(const struct queue* q) {
  return q->values + q->first;
}

struct moving_min* back(const struct queue* q) {
  return q->values + q->last;
}

void push_back(struct queue* q, int64_t value, int index) {
  q->last = (q->last + 1) % q->max_size;
  q->values[q->last].value = value;
  q->values[q->last].index = index;
  q->size++;
  assert(q->size <= q->max_size);
}

void pop_front(struct queue* q) {
  q->first = (q->first + 1) % q->max_size;
  q->size--;
  assert(q->size >= 0);
}

void pop_back(struct queue* q) {
  q->last = (q->last - 1);
  if (q->last < 0) {
    q->last = q->max_size - 1;
  }
  q->size--;
  assert(q->size >= 0);
}

void init_queue(struct queue* q, int k) {
  q->max_size = k;
  q->size = 0;
  q->first = 0;
  q->last = k - 1;
  q->values = malloc(sizeof(struct moving_min) * k);
}

void free_queue(struct queue* q) {
  free(q->values);
}

void print_queue(const struct queue* q) {
  int i;
  for (i = 0; i < q->size; ++i) {
    struct moving_min* val = q->values + ((q->first + i) % q->max_size);
    printf("[%d]=%d,%lld ", i, val->index, val->value);
  }
  printf("\n");
}

// Maintain a queue with the min value of the last k in front

void maintain_moving(int latest_index, int64_t latest_value,
                     struct queue* q) {
  // Remove the first element if its index is out of date
  if ((int64_t)front(q)->index <= latest_index - (int64_t)q->max_size) {
    pop_front(q);
  }
  // Remove elements with a greater value
  while (q->size > 0) {
    if (latest_value <= back(q)->value) {
      pop_back(q);
    } else {
      break;
    }
  }
  // Add the new element
  push_back(q, latest_value, latest_index);
}

int64_t shortest_path(int n, int k, int64_t* values) {
  struct queue q;
  int64_t shortest_path_value;
  int64_t value_sum = 0;
  int i;
  int64_t ret;
  init_queue(&q, k + 1);
  maintain_moving(0, 0, &q);
  for (i = 0; i < n; ++i) {
    value_sum += values[i];
    shortest_path_value = front(&q)->value + values[i];
    maintain_moving(i + 1, shortest_path_value, &q);
  }
  ret = value_sum - front(&q)->value;
  free_queue(&q);
  return ret;
}

int main() {
  int n, k, i;
  scanf("%d %d\n", &n, &k);
  int64_t* values = malloc(n * sizeof(int64_t));
  for (i = 0; i < n; ++i) {
    scanf("%lld\n", values + i);
  }
  printf("%lld", shortest_path(n, k, values));
  return 0;
}








In Python3 :





a=[]
b=[]
soln=[]
in1=[]
out=[]
n1=input("")
k1=n1.split()
n=int(k1[0])
k=int(k1[1])
lis=[]
number=[]

for i in range(0,n):
    d=input("")
    a.append(int(d))
    b.append(1) 
    in1.append(a[i])
    out.append(0)
    number.append(0)

number[n-1]=1
for i in range (1,k):
    in1[n-1-i]=in1[n-i]+a[n-i-1]
    number[n-i-1]=i+1
    out[n-1-i]=in1[n-i]
    
i=n-k-1
while (i>=0):
    out[i]=max(out[i+1],in1[i+1])
    if (number[i+1]<k and in1[i+1]>out[i+1]):
        number[i]=number[i+1]+1
        in1[i]=in1[i+1]+a[i]
    else :
        in1[i]=0
        j=0
        while(j<k):
            
            in1[i]=in1[i]+a[i+j]
            #print(a[i+j],i,in1[i])
            j=j+1
        number[i]=k
        sumi=a[i]
        j=1
        
        while (j<=k):
           #print(i,sumi+out[i+j],in1[i])
           if (sumi+out[i+j]>in1[i]):
                in1[i]=sumi+out[i+j]
                number[i]=j
                #print(i,j,sumi,in1[i])
           sumi=sumi+a[i+j]
           j=j+1
            
            
    i=i-1
#print(in1)
#print(out)
#print(number)
print(max(in1[0],out[0]))
                        








View More Similar Problems

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution →

Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution →

Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

View Solution →

Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

View Solution →

Tree Coordinates

We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For

View Solution →