zoukankan      html  css  js  c++  java
  • 美团2015 研发笔试 (2)

    题目

    一天之内股票价格变动n次,只能进行最多两次股票买卖,而且必须完成一次才能进行下一次买卖,也就是说只能 买—>卖 —>买—>卖 ;

    给出一天内 股票的售价,设计如何买卖能够获得最大收益,给出最大收益;

    输入:

    //第一行,一天能股票的价格种类
    6
    //第二行,给出价格数
    10 22 5 75 65 80

    输出:
    //一行 , 最大收益
    87

    分析

    题目要求,尽可能高效实现;

    想了许久,没有得出高效算法;

    一种实现

    #include <stdio.h>
    #include <stdlib.h>
    
    //获取单次购买股票的最大收益
    int fun(int *prices, int n)
    {
        int max, temp,i,j;
        temp = 0;
        max = 0;
    
        for (i = 0; i < n; i++)
        {
            temp = 0;
            for (j = i + 1; j < n; j++)
            {
                if (prices[j] > prices[i])
                {
                    temp = (prices[j] - prices[i]);
                    if (temp > max)
                        max = temp;
                }//if
            }//for
        }//for
        return max;
    }
    
    //获得两次购买股票的最大收益
    int maxIncome(int *prices, int n)
    {
        int max, temp , i , j;
        int *p;
        max = 0;
        temp = 0;
    
        for (i = 0; i < n; i++)
        {
            for (j = i + 1; j < n; j++)
            {
                if (prices[j] > prices[i])
                {
                    temp = 0;
                    temp += (prices[j] - prices[i]);
                    p = prices + j + 1;
                    temp = temp + fun(p, n - j-1);
                }
                if (temp > max)
                {
                    max = temp;
                }
            }//for
        }//for
        return max;
    }
    
    int main()
    {
        int n , tmp , *prices , ret , i;
    
        scanf_s("%d", &n);
        prices = (int *)malloc(n*sizeof(int));
    
        for (i = 0; i < n; i++)
        {
            scanf_s("%d", &tmp);
            prices[i] = tmp;
        }
    
        ret = maxIncome(prices, n);
    
        printf("%d
    ", ret);
    
        free(prices);
        system("pause");
        return 0;
    }
  • 相关阅读:
    计算机网络基础
    ansible
    CDH集群日常
    漏洞挖掘学习
    JDWP
    开源安全项目调研
    SMB漏洞汇总
    Windows账户LM/NTLM
    SMB知识汇总
    Memcache未授权漏洞
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214842.html
Copyright © 2011-2022 走看看