Leetcode's Medium collection (C + + implementation) eight

Source: Internet
Author: User

1 Pow (x, N)
The problem is recursive by dichotomy

Double Mypow (doublex,intN) {if(n==0)return 1;if(n<0) {n= (-N);x=1/x; } Double Res=mypow (x, n/2);if(n%2==0)        {returnRes*res; }Else{returnRes*res*x; }    }

2 Maximum Subarray
Find the contiguous subarray within an array (containing at least one number) which have the largest sum. For example, given the array [? 2,1,?3,4,?1,2,1,?5,4], the contiguous subarray [4,?1,2,1] have the largest sum = 6.
The problem can be solved by dynamic programming, d P[I]=d P[I?1]>0?d P[I?1]+Nums[I]:Nums[I] . Obviously, when the current maximum value is less than 0 o'clock, the next value is calculated less than 0 of the number discarded.

int maxSubArray(vector<int>& nums) {        int max=INT_MIN;        int n=nums.size();        int mid=0;        for(int i=0;i<n;i++)        {        //这里用mid,max替代dp数组以节省空间            mid=mid+nums[i];            mid=(nums[i]>=mid?nums[i]:mid);            if(mid>max)            {                max=mid;            }        }        return max;    }

Leetcode's Medium collection (C + + implementation) eight

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.