最大子数组和 leetcode java篇

news/2024/7/8 5:32:18

给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

子数组 是数组中的一个连续部分。

 

class Solution {
    public int maxSubArray(int[] ns) {
        int max = ns[0];
        int pre = 0;
        for(int x:ns){
            pre +=x;
            pre = Math.max(pre,x);
            max = Math.max(max,pre);
        }
        return max;
    }
}

 


http://www.niftyadmin.cn/n/3651725.html

相关文章

考试的最大困扰度 leetcode java篇

一位老师正在出一场由 n 道判断题构成的考试,每道题的答案为 true (用 T 表示)或者 false (用 F 表示)。老师想增加学生对自己做出答案的不确定性,方法是 最大化 有 连续相同 结果的题数。(也就…

Lonely Low

Have you ever been this lowthat you dont know where to go?Missing something you do long for,trying to get to heaven before they close the door?You walk slowly along the beach,seeing the sands of time sort of etch.You look around -- the sea is blue,shout …

SHAKESPEARE SONNETS LXVI

性能测试常见误区请看下面一个性能测试小案例:某公司OA产品的新版本即将发布。为了看看系统的性能,决定安排测试工程师A君执行性能测试任务。A君做法如下:1. 找到一台PC机,CPU主频1G,内存512M,……&a…

动态规划系列(1) leetcode java

第一题: 斐波那契数 (通常用 F(n) 表示)形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是: 核心思想: F(n)F(n−1)F(n−2) class Solution {public int fib(int n) {int f0 …

FEW MORE CUPS OF COFFEE铪铪

AUG.2,2005FEW MORE CUPS OF COFFEEby Kakuji FunegataDo I have to remind you,Whom I owe cups of coffee to ?I am and will be forever in your debtUntil I do you the favor at last.Is it alright that you I inviteTo have some coffee at any time you like ?To the…

动态规划系列(2) leetcode java

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? class Solution {public int climbStairs(int n) {int s 0;int e 1;int tmp 0;while(n-->0){tmp e;es;s tmp;}return e;} } 第二题: 给你…

买卖股票的最佳时机 leetcode java篇

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。 你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。 返回你可以从这笔交易中获取的最大利润。…

动态规划系列(3) leetcode java篇

第一题: 打家劫舍 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个代表…