234 lines
9.0 KiB
HTML
234 lines
9.0 KiB
HTML
|
|
<!DOCTYPE html>
|
|||
|
|
<html lang="zh-Hans">
|
|||
|
|
<head>
|
|||
|
|
<meta charset="UTF-8">
|
|||
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|||
|
|
<title>013. 最大子数组和 – 图解</title>
|
|||
|
|
<link rel="stylesheet" href="../shared/style.css">
|
|||
|
|
<style>
|
|||
|
|
.vis-area { min-height: 160px; padding: 16px 0; }
|
|||
|
|
.code-section { margin-top: 16px; }
|
|||
|
|
.tag { display: inline-block; padding: 2px 8px; border-radius: 6px; font-size: 12px; font-weight: 600; margin: 0 3px; }
|
|||
|
|
.tag.cur { background: #fff7ed; color: #9a3412; border: 1px solid #f59e0b; }
|
|||
|
|
.tag.best { background: #dcfce7; color: #166534; border: 1px solid #16a34a; }
|
|||
|
|
.summary-row { display: flex; gap: 24px; flex-wrap: wrap; margin-top: 12px; }
|
|||
|
|
.summary-item { display: flex; align-items: center; gap: 6px; font-size: 14px; }
|
|||
|
|
</style>
|
|||
|
|
</head>
|
|||
|
|
<body>
|
|||
|
|
<div class="container">
|
|||
|
|
<h1>🟡 013. 最大子数组和 <span class="badge medium">中等</span></h1>
|
|||
|
|
<p class="subtitle">分类:普通数组 | LeetCode Hot 100 | Kadane 算法</p>
|
|||
|
|
|
|||
|
|
<div class="controls" id="controls">
|
|||
|
|
<label for="inputArea">输入:</label>
|
|||
|
|
<input type="text" id="inputArea" placeholder="默认示例,可自定义">
|
|||
|
|
<button id="applyBtn" class="primary">生成图解</button>
|
|||
|
|
<select id="exampleSelect"></select>
|
|||
|
|
<span style="flex:1"></span>
|
|||
|
|
<button id="prevBtn">◀ 上一步</button>
|
|||
|
|
<button id="nextBtn">下一步 ▶</button>
|
|||
|
|
<button id="jumpBtn">⏭ 跳到结果</button>
|
|||
|
|
<button id="autoBtn">自动播放</button>
|
|||
|
|
<button id="resetBtn">重置</button>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<div class="pipeline" id="pipeline"></div>
|
|||
|
|
|
|||
|
|
<div class="hint info" id="hintBox">
|
|||
|
|
<span id="stepInfo"></span><br>
|
|||
|
|
<span id="hintText"></span>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<div class="panels">
|
|||
|
|
<div class="panel" id="mainPanel">
|
|||
|
|
<h3>📊 可视化</h3>
|
|||
|
|
<div class="vis-area" id="vizArea">点击「生成图解」开始</div>
|
|||
|
|
</div>
|
|||
|
|
<div class="panel-grid">
|
|||
|
|
<div class="panel" id="detailPanel">
|
|||
|
|
<h3>📝 当前步骤详情</h3>
|
|||
|
|
<div id="detailContent">等待开始...</div>
|
|||
|
|
</div>
|
|||
|
|
<div class="panel" id="resultPanel">
|
|||
|
|
<h3>✅ 结果</h3>
|
|||
|
|
<div id="resultContent">等待完成...</div>
|
|||
|
|
</div>
|
|||
|
|
</div>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<div class="panel code-section">
|
|||
|
|
<h3>💻 参考代码(Python)</h3>
|
|||
|
|
<div id="codeArea"></div>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<footer>Powered by QwenPaw · 图解算法 · LeetCode Hot 100</footer>
|
|||
|
|
</div>
|
|||
|
|
|
|||
|
|
<script src="../shared/algo-viz.js"></script>
|
|||
|
|
<script>
|
|||
|
|
"use strict";
|
|||
|
|
(function() {
|
|||
|
|
const examples = [
|
|||
|
|
{input: [-2,1,-3,4,-1,2,1,-5,4], label: '示例1: [-2,1,-3,4,-1,2,1,-5,4]'},
|
|||
|
|
{input: [1], label: '示例2: [1]'},
|
|||
|
|
{input: [5,4,-1,7,8], label: '示例3: [5,4,-1,7,8]'},
|
|||
|
|
{input: [-1,-2,-3,-4], label: '全负: [-1,-2,-3,-4]'},
|
|||
|
|
];
|
|||
|
|
let nums, steps, stepCtrl;
|
|||
|
|
|
|||
|
|
function buildSteps(arr) {
|
|||
|
|
nums = [...arr];
|
|||
|
|
steps = [];
|
|||
|
|
const n = nums.length;
|
|||
|
|
let curSum = nums[0], maxSum = nums[0];
|
|||
|
|
let curStart = 0, curEnd = 0;
|
|||
|
|
let bestStart = 0, bestEnd = 0;
|
|||
|
|
|
|||
|
|
steps.push({
|
|||
|
|
stage:'init', i:0, curSum, maxSum,
|
|||
|
|
curStart:0, curEnd:0, bestStart:0, bestEnd:0,
|
|||
|
|
msg:`初始化:current = max = nums[0] = ${nums[0]},当前子数组范围 [0,0]`
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
for (let i = 1; i < n; i++) {
|
|||
|
|
const extendSum = curSum + nums[i];
|
|||
|
|
if (extendSum > nums[i]) {
|
|||
|
|
curSum = extendSum;
|
|||
|
|
curEnd = i;
|
|||
|
|
steps.push({
|
|||
|
|
stage:'extend', i, curSum, maxSum,
|
|||
|
|
curStart, curEnd, bestStart, bestEnd,
|
|||
|
|
msg:`i=${i}: nums[${i}]=${nums[i]},延伸更优 (${curSum - nums[i]})+${nums[i]}=${curSum} ≥ ${nums[i]},当前子数组 [${curStart},${curEnd}],curSum=${curSum}`
|
|||
|
|
});
|
|||
|
|
} else {
|
|||
|
|
curSum = nums[i];
|
|||
|
|
curStart = i; curEnd = i;
|
|||
|
|
steps.push({
|
|||
|
|
stage:'restart', i, curSum, maxSum,
|
|||
|
|
curStart, curEnd, bestStart, bestEnd,
|
|||
|
|
msg:`i=${i}: nums[${i}]=${nums[i]},重新开始更优 (${extendSum - nums[i]})+${nums[i]}=${extendSum} < ${nums[i]},新子数组 [${curStart},${curEnd}],curSum=${curSum}`
|
|||
|
|
});
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
if (curSum > maxSum) {
|
|||
|
|
const oldMax = maxSum;
|
|||
|
|
maxSum = curSum;
|
|||
|
|
bestStart = curStart; bestEnd = curEnd;
|
|||
|
|
steps.push({
|
|||
|
|
stage:'update_max', i, curSum, maxSum,
|
|||
|
|
curStart, curEnd, bestStart, bestEnd,
|
|||
|
|
msg:`i=${i}: curSum=${curSum} > maxSum=${oldMax},更新最大子数组和为 ${maxSum},范围 [${bestStart},${bestEnd}]`
|
|||
|
|
});
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
steps.push({
|
|||
|
|
stage:'done', i:n-1, curSum, maxSum,
|
|||
|
|
curStart, curEnd, bestStart, bestEnd,
|
|||
|
|
msg:`遍历完毕,最大子数组和 = ${maxSum},范围 [${bestStart},${bestEnd}]`
|
|||
|
|
});
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
function render(step) {
|
|||
|
|
const s = steps[step];
|
|||
|
|
|
|||
|
|
// Build highlights: current subarray = orange, best subarray = green override
|
|||
|
|
const hl = {};
|
|||
|
|
for (let i = s.curStart; i <= s.curEnd; i++) hl[i] = 'orange';
|
|||
|
|
for (let i = s.bestStart; i <= s.bestEnd; i++) hl[i] = 'green';
|
|||
|
|
if (s.i >= 0 && s.i < nums.length) hl[s.i] = 'active';
|
|||
|
|
|
|||
|
|
const pointers = {};
|
|||
|
|
if (s.i >= 0) pointers['i'] = s.i;
|
|||
|
|
|
|||
|
|
let viz = '<div style="margin-bottom:8px;font-size:13px;color:#475569;">原始数组</div>';
|
|||
|
|
viz += renderArray(nums, {highlights: hl, pointers});
|
|||
|
|
|
|||
|
|
// Subarray labels below
|
|||
|
|
viz += '<div style="margin-top:12px;display:flex;gap:16px;flex-wrap:wrap;font-size:13px;">';
|
|||
|
|
viz += `<span class="tag cur">当前子数组 [${s.curStart},${s.curEnd}] 和 = ${s.curSum}</span>`;
|
|||
|
|
viz += `<span class="tag best">最大子数组 [${s.bestStart},${s.bestEnd}] 和 = ${s.maxSum}</span>`;
|
|||
|
|
viz += '</div>';
|
|||
|
|
|
|||
|
|
// DP formula
|
|||
|
|
viz += '<div class="formula-box" style="margin-top:12px;">';
|
|||
|
|
viz += `<code>dp[i] = max(nums[i], dp[i-1] + nums[i])</code><br>`;
|
|||
|
|
if (s.stage !== 'init') {
|
|||
|
|
viz += `当前 i=${s.i}: dp[${s.i}] = max(${nums[s.i]}, ${s.curSum === nums[s.i] && s.stage==='restart' ? 'prev+'+nums[s.i] : 'prev+' + nums[s.i]}) = <b>${s.curSum}</b>`;
|
|||
|
|
}
|
|||
|
|
viz += '</div>';
|
|||
|
|
|
|||
|
|
$('vizArea').innerHTML = viz;
|
|||
|
|
|
|||
|
|
// Detail panel
|
|||
|
|
let detail = '<div class="calc-block">' + s.msg + '</div>';
|
|||
|
|
detail += '<div class="summary-row">';
|
|||
|
|
detail += `<div class="summary-item"><span class="tag cur">curSum</span> <b>${s.curSum}</b></div>`;
|
|||
|
|
detail += `<div class="summary-item"><span class="tag best">maxSum</span> <b>${s.maxSum}</b></div>`;
|
|||
|
|
detail += '</div>';
|
|||
|
|
$('detailContent').innerHTML = detail;
|
|||
|
|
|
|||
|
|
// Result
|
|||
|
|
if (s.stage === 'done') {
|
|||
|
|
const sub = nums.slice(s.bestStart, s.bestEnd + 1);
|
|||
|
|
$('resultContent').innerHTML = `<div class="final-answer">
|
|||
|
|
最大子数组和 = <b>${s.maxSum}</b><br>
|
|||
|
|
子数组: [${sub.join(', ')}]<br>
|
|||
|
|
范围: 索引 [${s.bestStart}, ${s.bestEnd}]
|
|||
|
|
<div class="complexity">时间复杂度 O(n) | 空间复杂度 O(1) | Kadane 算法</div>
|
|||
|
|
</div>`;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
$('hintText').textContent = s.msg;
|
|||
|
|
|
|||
|
|
const stages = [
|
|||
|
|
['init','初始化'],['extend','延伸'],['restart','重新开始'],['update_max','更新最大'],['done','完成']
|
|||
|
|
];
|
|||
|
|
$('pipeline').innerHTML = stages.map(([k,l]) =>
|
|||
|
|
`<span class="pipe-step ${s.stage===k?'active':''}">${l}</span>`
|
|||
|
|
).join('<i>→</i>');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
function init() {
|
|||
|
|
const sel = $('exampleSelect');
|
|||
|
|
examples.forEach((e,i) => { sel.innerHTML += `<option value="${i}">${e.label}</option>`; });
|
|||
|
|
$('inputArea').value = JSON.stringify(examples[0].input);
|
|||
|
|
buildSteps(examples[0].input);
|
|||
|
|
stepCtrl = new StepController({onStep: render});
|
|||
|
|
stepCtrl.setSteps(steps.map((_,i)=>i));
|
|||
|
|
$('stepInfo').textContent = '步骤 1 / ' + steps.length;
|
|||
|
|
stepCtrl.onStep = (idx) => { render(idx); $('stepInfo').textContent = `步骤 ${idx+1} / ${steps.length}`; };
|
|||
|
|
$('applyBtn').onclick = () => {
|
|||
|
|
try {
|
|||
|
|
const arr = JSON.parse($('inputArea').value);
|
|||
|
|
if (!Array.isArray(arr) || arr.length === 0) throw new Error();
|
|||
|
|
buildSteps(arr); stepCtrl.setSteps(steps.map((_,i)=>i)); render(0);
|
|||
|
|
$('stepInfo').textContent = '步骤 1 / ' + steps.length;
|
|||
|
|
} catch(e) { alert('请输入合法非空 JSON 数组,例如 [-2,1,-3,4,-1,2,1,-5,4]'); }
|
|||
|
|
};
|
|||
|
|
$('exampleSelect').onchange = () => {
|
|||
|
|
const e = examples[parseInt($('exampleSelect').value)];
|
|||
|
|
$('inputArea').value = JSON.stringify(e.input);
|
|||
|
|
buildSteps(e.input); stepCtrl.setSteps(steps.map((_,i)=>i)); render(0);
|
|||
|
|
};
|
|||
|
|
$('prevBtn').onclick = () => stepCtrl.prev();
|
|||
|
|
$('nextBtn').onclick = () => stepCtrl.next();
|
|||
|
|
$('jumpBtn').onclick = () => stepCtrl.jumpToEnd();
|
|||
|
|
$('autoBtn').onclick = () => { const on = stepCtrl.toggleAuto(); $('autoBtn').textContent = on ? '暂停' : '自动播放'; };
|
|||
|
|
$('resetBtn').onclick = () => { stepCtrl.reset(); $('autoBtn').textContent = '自动播放'; };
|
|||
|
|
}
|
|||
|
|
init();
|
|||
|
|
|
|||
|
|
$('codeArea').innerHTML = renderCode(`def maxSubArray(nums):
|
|||
|
|
cur = max_sum = nums[0]
|
|||
|
|
for i in range(1, len(nums)):
|
|||
|
|
# dp[i] = max(nums[i], dp[i-1] + nums[i])
|
|||
|
|
cur = max(nums[i], cur + nums[i])
|
|||
|
|
max_sum = max(max_sum, cur)
|
|||
|
|
return max_sum`, {lang:'Python'});
|
|||
|
|
})();
|
|||
|
|
</script>
|
|||
|
|
</body>
|
|||
|
|
</html>
|