动态规划 53:Maximum Subarray,152:Maximum Subarray,266. Palindrome Permutation 回文全排列...

 

题意:寻找子数组的和最大。

思路:设置dp数组来保存到第i位的最大和。

判断第i-1位的正负,若dp[i-1]<0 则 dp[i] = nums[i]; 若 dp[i-1] > 0 则 dp[i] = dp[i-1] +nums[i];

最后用 max_num = max(max_num, dp[i]); 来存储最大的和。

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int len = nums.size();
        if(len == 0) return 0;
        if(len == 1) return nums[0];
        vector<int> dp(len, 0);  //dp[i]: 以第i个元素为结尾的最大子序列和
        dp[0] = nums[0];
        int max_num = dp[0];
        for(int i=1; i<len; i++){
            if(dp[i-1] > 0)
                dp[i] = dp[i-1] +nums[i];
            else
                dp[i] = nums[i];
             
        }
        return max_num;
    }
};

 

题意:求子数组(数组里的数是连续)的最大乘积。

思路:因为数组里有负号,所以用两个数组dp_max 和 dp_min 分别保存到当前位置i的最大值和最小值。

状态转移方程:           

dp_max[i%2] = max( max(dp_max[(i-1)%2]*nums[i], nums[i]), dp_min[(i-1)%2]*nums[i]);
dp_min[i%2] = min(min(dp_min[(i-1)%2]*nums[i], nums[i]), dp_max[(i-1)%2]*nums[i]);

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int n = nums.size();
        if(n==0) return 0;
        int dp_max[2]={nums[0], 0}, dp_min[2]={nums[0], 0} ;
        int ans = nums[0];
        for(int i=1; i<n; i++){
            dp_max[i%2] = max( max(dp_max[(i-1)%2]*nums[i], nums[i]), dp_min[(i-1)%2]*nums[i]);
            dp_min[i%2] = min(min(dp_min[(i-1)%2]*nums[i], nums[i]), dp_max[(i-1)%2]*nums[i]);
            ans = max(ans, dp_max[i%2]);
        }
        
        return ans;
    }
};

 

266. Palindrome Permutation 回文全排列

Given a string, determine if a permutation of the string could form a palindrome.

Example 1:

Input: "code"
Output: false

Example 2:

Input: "aab"
Output: true

Example 3:

Input: "carerac"
Output: true

Hint:

  1. Consider the palindromes of odd vs even length. What difference do you notice?
  2. Count the frequency of each character.
  3. If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?

 

转载于:https://www.cnblogs.com/Bella2017/p/10957868.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值