Fork me on GitHub

数组分为两部分,使得其和相差最小

  • 题目:将一个数组分成两部分,不要求两部分所包含的元素个数相等,要求使得这两个部分的和的差值最小。比如对于数组{1,0,1,7,2,4},可以分成{1,0,1,2,4}和{7},使得这两部分的差值最小。

思路:这个问题可以转化为求数组的一个子集,使得这个子集中的元素的和尽可能接近sum/2,其中sum为数组中所有元素的和。这样转换之后这个问题就很类似0-1背包问题了:在n件物品中找到m件物品,他们的可以装入背包中,且总价值最大不过这里不考虑价值,就考虑使得这些元素的和尽量接近sum/2。

下面列状态方程: 
dp[i][j]表示前i件物品中,总和最接近j的所有物品的总和,其中包括两种情况:

  1. 第i件物品没有包括在其中
  2. 第i件物品包括在其中

如果第i件物品没有包括在其中,则dp[i][j] = dp[i-1][j] 
如果第i件物品包括在其中,则dp[i][j] = dp[i-1][j-vec[i]]

当然,这里要确保j-vec[i] >= 0。

所以状态转移方程为: 

dp[i][j] = max(dp[i-1][j],dp[i-1][j-vec[i]]+vec[i]);

 for (int i = 1; i <= len; ++i) {  
        for (int j = 1; j <= sum / 2; ++j) {  
            if(j>=vec[i-1])
                   dp[i][j] = max(dp[i-1][j],dp[i-1][j-vec[i-1]]+vec[i-1]);  
            else 
                   dp[i][j] = dp[i - 1][j];  
        }  
    }  

将1~n个整数按字典顺序进行排序,返回排序后第m个元素

 字典序(今日头条2017秋招真题)

  • Leetcode学习—— Array Partition I

Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), …, (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

给出一个长度为 2n 的整数数组,你的任务是将这些整数分成n组,每组两个一对,并求得 所有分组中较小的数 的总和(这个总和的值要尽可能的大)

Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4.

    Note:
    n is a positive integer, which is in the range of [1, 10000].
    All the integers in the array will be in the range of [-10000, 10000].

思路:将整个数组升序排列,从下标为 0 处开始,每隔两个 取一个,并求和

class Solution(object):
    def arrayPartitionI(self, nums):
        return sum(sorted(nums)[::2])

 

posted @ 2018-05-24 20:54  ranjiewen  阅读(12407)  评论(0编辑  收藏  举报