最大子串的题目

谁践踏了优雅 2022-12-11 15:01 114阅读 0赞

1、连续子数组的最大和

  1. var theMaxSum = function (arr) {
  2. let max = -Infinity;
  3. arr.reduce((total, item) => {
  4. if (total > 0) {
  5. total += item;
  6. } else {
  7. total = item;
  8. }
  9. max = max > total ? max : total;
  10. return total;
  11. }, 0)
  12. return max;
  13. };

2、数组中和最大的子数组

  1. function childArrayOfTheMaxSum(arr) { // 基于上面的方法进行求解
  2. let max = -Infinity;
  3. // 求出最大值
  4. arr.reduce((total, item) => {
  5. if (total > 0) {
  6. total += item;
  7. } else {
  8. total = item;
  9. }
  10. max = max > total ? max : total
  11. return total
  12. }, 0)
  13. // 根据最大值去找子数组
  14. for (let i = 0; i < arr.length; i++) {
  15. let sum = 0;
  16. let res= [];
  17. for (let j = i; j < arr.length; j++) {
  18. sum += arr[j];
  19. res.push(arr[j])
  20. if (sum === max) {
  21. return res
  22. }
  23. }
  24. }
  25. }

3、无重复字符的最长子串的长度

  1. var lengthOfLongestSubstring = function (str) {
  2. let temp = ''; // 中间变量,用于比较操作
  3. let max = 0; // 最长子串的长度
  4. let resStr = ''; // 保存最长子串
  5. for (let i = 0; i < str.length; i++) {
  6. if (temp.indexOf(str[i]) === -1) {
  7. temp += str[i]
  8. if (max < temp.length) {
  9. max = temp.length;
  10. resStr = temp;
  11. }
  12. } else {
  13. temp = temp.slice(temp.indexOf(str[i]) + 1) + str[i]
  14. }
  15. }
  16. return [max, resStr]
  17. };

发表评论

表情:
评论列表 (有 0 条评论,114人围观)

还没有评论,来说两句吧...

相关阅读

    相关 连续

    题描述: 给定一个由数字组成的数组,求出和最大的子数组 求解方法: 1.暴力法 选取所有连续和的可能性,O(n^2) 2.分析法 当遍历到第i个元素时,判断在...