zoukankan      html  css  js  c++  java
  • LeetCode 53. Maximum Subarray

    53. Maximum Subarray

    Difficulty: Medium

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

    For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6.

    More practice:

    If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

    典型的 DP ,解题时间复杂度 O(n)

    递推方程

    curr(i) = max{curr(i-1), 0} + arr[i]
    
    if  curr(i) > ret    
    then    ret = curr(i)
    

    解题代码

    int maxSubArray(int* nums, int numsSize) {
    	int curr = 0;
    	int ret = nums[0];
    
    	for (int i = 0; i < numsSize; i++) {
    		if (curr > 0) {
    			curr += nums[i];
    		} else {
    			curr = nums[i];
    		}
    
    		if (curr > ret) {
    			ret = curr;
    		}
    	}
    
    	return ret;
    }
    

    cost : 4ms

  • 相关阅读:
    错误机制
    IO文件
    lua与c的交互(运用)
    lua与c的交互(函数专用)
    string库
    元表

    模块与包
    zsh终端下,配置环境变量使用~/.zshrc
    MX150+python3.7+CUDA10.0+Tensorflow-gpu1.13安装记录
  • 原文地址:https://www.cnblogs.com/fengyubo/p/5724293.html
Copyright © 2011-2022 走看看