微软夏令营笔试测验第一题 Array Partition

时间限制:10000ms
单点时限:1000ms
内存限制:256MB
描述
Given an integer array A1, A2 … AN, you are asked to split the array into three continuous parts: A1, A2 … Ap | Ap+1, Ap+2, … Aq | Aq+1, Aq+2, … AN.

Let S1, S2 and S3 denote the sums of each part:

S1 = A1 + A2 + … + Ap

S2 = Ap+1 + Ap+2 + … + Aq

S3 = Aq+1 + Aq+2 + … + AN

A partition is acceptable if and only if the differences between S1, S2 and S3 (i.e. |S1 - S2|, |S2 - S3|, |S3 - S1|) are no more than 1.

Can you tell how many different partitions are acceptable?

输入
The first line contains an integer N.

The second line contains N integers, A1, A2 … AN.

For 30% of the data, N ≤ 100

For 70% of the data, N ≤ 1000

For 100% of the data, N ≤ 100000, -1000000 ≤ Ai ≤ 1000000

输出
The number of acceptable partitions.

样例解释
The three acceptable partitions are:

3 | 2 | 1 0 2

3 | 2 1 | 0 2

3 | 2 1 0 | 2

样例输入
5
3 2 1 0 2
样例输出
3

动态规划问题,按照题目的要求只有可能出现三种情况,x,x,x;x,x,x+1;x,x,x-1;很明显这三种情况是互斥的。
对于每一种情况有O(n)的算法,首先从后向前计算,用一个数组保存当前位置及之后的位置包含多少个和为sum的情况,用一个数组进行统计,之后采用从前到后遍历,遍历确定前半段的和等于固定值之后寻找跳过一个的位置存储的值(保证最少有一个划分元素),相加即可


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值