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

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →

Game of Two Stacks

Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f

View Solution →

Largest Rectangle

Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle

View Solution →