CVTE 2019 Web前端开发在线笔试题

版权声明:本文为博主原创文章,未经博主允许不得转载。欢迎关注我的微博@叮當了個和諧 https://blog.csdn.net/qq_25073545/article/details/82792654

在这里插入图片描述

编程题1:

题目:数组两数和为定值
原题:leetcode1 Two Sum

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [2,7]


function fin(nums,tag) {
    var re=[];
    for(var i=0;i<nums.length;i++){
        for(var j=i+1;j<nums.length;j++){
            if(nums[i]+nums[j]==tag){
                re[0]=nums[i];
                re[1]=nums[j]
            }
        }
    }
    return re

}

var nums=[2,7,11,15]
var t=9;
console.log(fin(nums,t))

编程题2

题目:股票最大利润
原题:leetcode122 Best Time to Buy and Sell Stock II

假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。
如果你最多只允许完成一次交易,设计一个算法来找出最大利润。
实例:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

function maxProfit(prices) {
    var sum=0;
    let len=prices.length;
    for (let i = 0; i <= len; i++ ) {
        if(prices[i]<prices[i+1]){
            sum+=prices[i+1]-prices[i];
        }
    }
    return sum;
};
var arrr=[7,6,5,4,3,2,1]
console.log(maxProfit(arrr))

猜你喜欢

转载自blog.csdn.net/qq_25073545/article/details/82792654