Poker Hands

Interview

Time limit1sMemory limit128 MB

Summary
Given card counts per rank, find the fewest contiguous-rank straights whose unit cards sum to exactly those counts.
Level

Medium7 of 10

Topics
Greedy, Array, Implementation, Prefix sum
Solved
No attempts yet

Problem

Bessie and her friends are playing a special version of poker. The deck has NN (1≤N≤1000001 \le N \le 100000) distinct ranks, numbered 11 through NN (an ordinary deck has N=13N = 13).

In this game there is exactly one kind of hand a cow may play: choose two ranks ii and jj with i≤ji \le j, then play exactly one card of every rank from ii to jj inclusive. Such a hand is called a straight.

Bessie currently holds aia_i cards of rank ii (0≤ai≤1000000 \le a_i \le 100000). Find the minimum number of straights she must play to get rid of all of her cards.

Input

  • The first line contains the integer NN.
  • Among the next NN lines, the (i+1)(i+1)-th line contains aia_i, the number of cards of rank ii.

Output

Print a single integer: the minimum number of straights Bessie must play to get rid of all of her cards.

Hint

For the sample case, Bessie can play a straight from 11 to 55, a straight from 11 to 22, a straight from 44 to 55, two straights from 22 to 22, and a straight from 55 to 55, for a total of 6 hands needed to discard all of her cards.

Examples3

  1. Example 1

    Input
    5
    2
    4
    1
    2
    3
    
    Expected output
    6
    
  2. Example 2

    Input
    1
    5
    
    Expected output
    5
    
  3. Example 3

    Input
    5
    1
    2
    3
    4
    5
    
    Expected output
    5