LeetCode maximum sub order and / length of last word / plus one

53. Maximum suborder sum Given an integer array nums, find a continuous subarray with the largest sum (subarray contains at least one element), and r...
53. Maximum suborder sum

Given an integer array nums, find a continuous subarray with the largest sum (subarray contains at least one element), and return its maximum sum.

Example:

Input: [- 2,1, - 3,4, - 1,2,1, - 5,4],
Output: 6
Explanation: the sum of continuous subarrays [4, - 1,2,1] is the largest, which is 6.

class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ l = len(nums) i = 0 sum = 0 MaxSum = nums[0] while i < l: sum += nums[i] if sum > MaxSum: MaxSum = sum if sum < 0: sum = 0 i += 1 return MaxSum

class Solution(object): def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ result = nums[:] maxSum = nums[0] for i in range(1,len(nums)): if result[i-1]>0: result[i] = nums[i] + result[i-1] #Compare the size of the current value with the sum of the previous values. If the current value is larger, take the current value and discard the sum of the previous values if result[i]>maxSum: maxSum = result[i] return maxSum

58. Length of last word

Given a string containing only uppercase and lowercase letters and spaces', returns the length of its last word.

If the last word does not exist, return 0.

Description: a word is a string of letters without any spaces.

Example:

Type: "Hello World"
Output: 5

Note: split doesn't work when s = or or a!

class Solution(object): def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ lenword = 0 isAlpha = False for i in range(len(s)-1, -1, -1): tmp = s[i] if isAlpha == True and tmp.isalpha() == False: break if tmp.isalpha(): isAlpha = True lenword += 1 return lenword

66. plus one

Given a nonnegative integer represented by a nonempty array of integers, add one to the number.

The highest number is placed at the top of the array, and each element of the array only stores one number.

You can assume that except for the integer 0, this integer does not start with zero.

Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: the input array represents the number 123.

Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: the input array represents the number 4321.

class Solution(object): def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ num = '' for i in digits: num += str(i) new_num = str(int(num) + 1) new_list = [i for i in new_num] return new_list

class Solution(object): def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ if len(digits) == 0: digits = [1] elif digits[-1] == 9: digits = self.plusOne(digits[:-1]) digits.extend([0]) else: digits[-1] += 1 return digits

2 December 2019, 10:42 | Views: 4256

Add new comment

For adding a comment, please log in
or create account

0 comments