leetcode题解日练--2016.8.29

﻿﻿###不给自己任何借口

1、数位相加；

2、最大子序列乘积

——安东尼《给不二的情书》

258. Add Digits | Difficulty: Easy

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

tag：数学

1、

class Solution {
public:
int addDigits(int num) {
return 1 + (num - 1) % 9;
}
};

152. Maximum Product Subarray | Difficulty: Medium

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

tag：数组|DP

1、类似于连续最大子序列和的方法，但是需要保留一个最大一个最小，因为有正有负，如果碰到负数需要更改之前保留的最大与最小。

class Solution {
public:
int maxProduct(vector<int>& nums) {
int n=nums.size();
if(n==0)    return 0;
int res = nums[0];
for(int i=1,imax = res,imin = res;i<n;i++)
{
if(nums[i]<0)   swap(imax,imin);
imax = max(nums[i],nums[i]*imax);
imin = min(nums[i],nums[i]*imin);
res = max(res,imax);
}
return res;
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：leetcode题解日练--2016.8.29 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)