Task description

A non-empty zero-indexed array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P ≤ Q < N, is called a slice of array A. Thesum of a slice (P, Q) is the total of A[P] + A[P+1] + ... + A[Q].

Write a function:

class Solution { public int solution(int[] A); }

that, given an array A consisting of N integers, returns the maximum sum of any slice of A.

For example, given array A such that:

A[0] = 3 A[1] = 2 A[2] = -6 A[3] = 4 A[4] = 0

the function should return 5 because:

  • (3, 4) is a slice of A that has sum 4,
  • (2, 2) is a slice of A that has sum −6,
  • (0, 1) is a slice of A that has sum 5,
  • no other slice of A has sum greater than (0, 1).

Assume that:

  • N is an integer within the range [1..1,000,000];
  • each element of array A is an integer within the range [−1,000,000..1,000,000];
  • the result will be an integer within the range [−2,147,483,648..2,147,483,647].

Complexity:

  • expected worst-case time complexity is O(N);
  • expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified

Solution

 
Programming language used: Java
Total time used: 25 minutes
Code: 14:21:19 UTC, java, final, score:  100
// you can also use imports, for example:
// import java.util.*; // you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
import java.util.Arrays;
class Solution {
public int solution(int[] A) {
// write your code in Java SE 8
int max_ending = A[0];
int max_slice = A[0];
for(int i=1; i<A.length; i++){
max_ending = Math.max(max_ending + A[i], A[i]);
max_slice = Math.max(max_slice, max_ending);
}
return max_slice;
}
}
https://codility.com/demo/results/trainingDWA6ZF-77M/

最新文章

  1. MySQL执行计划解读
  2. Android不同屏幕适配
  3. 【Excel】Excel根据单元格背景色求和
  4. ARP协议的报文格式
  5. php 二分查找
  6. JAVA 对象的转型
  7. ADO.NET中的DataReader详解
  8. JDK,JRE,JVM区别与联系-理解与概括
  9. Oracle数据库中的违规策略规则的修正
  10. jQuery(1)——了解jQuery
  11. log4g 使用教程
  12. FTP、FTPS和SFTP
  13. Javascript中的this关键字用法详解
  14. AI deeplab
  15. jquery向Django后台发送数组
  16. Individual Reading Assignment
  17. shell脚本学习之参数传递
  18. Django 前端Wbe框架
  19. centos下快速安装JDK
  20. input type=&quot;number&quot;时,maxlength不起作用怎么解决

热门文章

  1. leetcode先刷_Valid Sudoku
  2. C++请求web service与xml解析
  3. 数学概念 —— 奇异性(Singularity,Vertical tangent)
  4. Linux input
  5. 【Leetcode】Linked List Cycle II
  6. 怎么会float交换器int
  7. WPF中StringFormat的用法
  8. .net core config读取
  9. EF ModelFirst 步骤
  10. Objective