Careercup - Facebook面试题 - 23594662

2014-05-02 03:19

题目链接

原题:

Given a sequence of numbers A(1) ..A(n), find the continuous subsequenceA(i)..A(j) for which the sum of elements is maximum. 



condition: we should not select two contiguous numbers

题目:此人的描述简直就是自相矛盾,我的第一念头是这人肯定是个草包,题目都看不懂就从别的地方把题目复制过来了。这题的实际意思,是说允许你从一个长度为n的整数数组中,任意选取若干个元素,使得加起来的和最大,但是选取的任何元素不能存在相邻的情况。

解法:因为不能相邻,所以进行动态规划只需要记录两个状态。空间也只需要O(1)。递推关系为dp[i] = max(dp[i - 1], dp[i - 2], dp[i - 2] + arr[i])。

代码:

 1 // http://www.careercup.com/question?id=23594662

 2 #include <algorithm>

 3 #include <iostream>

 4 #include <vector>

 5 using namespace std;

 6 

 7 void myswap(int &x, int &y)

 8 {

 9     if (x == y) {

10         return;

11     }

12 

13     x = x ^ y;

14     y = x ^ y;

15     x = x ^ y;

16 }

17 

18 int maxDiscontiguousSum(vector<int> &v)

19 {

20     int i, n;

21     int sum1, sum2, sum3;

22     

23     n = (int)v.size();

24     if (n == 0) {

25         return 0;

26     } else if (n == 1) {

27         return v[0];

28     }

29     

30     sum1 = v[0];

31     for (i = 1; i < n; ++i) {

32         sum1 = v[i] > sum1 ? v[i] : sum1;

33     }

34     if (sum1 <= 0) {

35         return sum1;

36     }

37     

38     sum1 = v[0];

39     sum2 = max(v[0], v[1]);

40     sum3 = sum2;

41     for (i = 2; i < n; ++i) {

42         sum3 = max(sum2, (v[i] > 0 ? sum1 + v[i] : sum1));

43         sum1 = sum2;

44         sum2 = sum3;

45     }

46     

47     return sum3;

48 }

49 

50 int main()

51 {

52     vector<int> v;

53     int n;

54     int i;

55     

56     while (cin >> n && n > 0) {

57         v.resize(n);

58         for (i = 0; i < n; ++i) {

59             cin >> v[i];

60         }

61         cout << maxDiscontiguousSum(v) << endl;

62         v.clear();

63     }

64     

65     return 0;

66 }

 

你可能感兴趣的:(Facebook)