首页 > 其他分享 > leetcode_数据结构_入门_121. 买卖股票的最佳时机

leetcode_数据结构_入门_121. 买卖股票的最佳时机

时间:2023-01-13 10:13:48浏览次数:45  
标签:minprice int maxprofit public 121 差值 prices 数据结构 leetcode

121. 买卖股票的最佳时机

 

 

问题:

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。
设计一个算法来计算你所能获取的最大利润。

返回可以从这笔交易中获取的最大利润,
如果不能获取任何利润,返回 0 。


思路:

我们需要找出给定数组中两个数字之间的最大差值(即,最大利润)★。
此外,第二个数字(卖出价格)必须大于第一个数字(买入价格)。

形式上,对于每组 i 和 j(其中 j > i)
我们需要找出 max(prices[j]−prices[i])。

 

 

 

代码:

 

main函数

package DataStructure_start;

public class DS20230113 {

    public static void main(String[] args) {

        int[] prices = {6, 8, 3, 4, 8, 9, 1};
        int[] prices2 = {7, 1, 5, 3, 6, 4};
        int maxProfit = maxProfit(prices);
        int maxProfit2 = maxProfit2(prices2);

        System.out.println(maxProfit);
        System.out.println(maxProfit2);
    }
}


方法一:暴力法

思路:
挨个遍历两遍,找到两个数,计算出最大差值

复杂度分析
时间复杂度:O(n^2),循环运行 n (n-1)/2次。
空间复杂度:O(1)只使用了常数个变量。

    public static int maxProfit(int[] prices) {

        int maxprofit = 0;

//        第一遍遍历
        for (int i = 0; i < prices.length - 1; i++) {
//            紧跟着遍历第二个数
            for (int j = i + 1; j < prices.length; j++) {

//                设置profit为两数的差值
                int profit = prices[j] - prices[i];
//                如果差值大于“目前的”最大值
                if (profit > maxprofit) {
//                    则将目前的差值赋值给maxfprofit
                    maxprofit = profit;
                }
            }
        }
//        返回最大差值
        return maxprofit;
    }


方法二:一次遍历

我们来假设自己来购买股票。
随着时间的推移,每天我们都可以选择出售股票与否。
那么,假设在第 i 天,如果我们要在今天卖股票,那么我们能赚多少钱呢?

显然,如果我们真的在买卖股票,我们肯定会想:
如果我是在历史最低点买的股票就好了!
太好了,在题目中,我们只要用一个变量记录一个历史最低价格 minprice,我们就可以假设自己的股票是在那天买的。
那么我们在第 i 天卖出股票能得到的利润就是 prices[i] - minprice。

因此,我们只需要遍历价格数组一遍,记录历史最低点,然后在每一天考虑这么一个问题:
如果我是在历史最低点买进的,那么我今天卖出能赚多少钱?
当考虑完所有天数之时,我们就得到了最好的答案。


复杂度分析

时间复杂度:O(n),只需要遍历一次。
空间复杂度:O(1),只使用了常数个变量。

    public static int maxProfit2(int prices[]) {

        int minprice = Integer.MAX_VALUE;
        int maxprofit = 0;

//        遍历一次
        for (int i = 0; i < prices.length; i++) {
//            将小的值赋值给minprice(找最低点)
            if (prices[i] < minprice) {
                minprice = prices[i];
//                如果差值大于maxprofit,则将最大差值赋值给maxprofit
            } else if (prices[i] - minprice > maxprofit) {
                maxprofit = prices[i] - minprice;
            }
        }
        return maxprofit;
    }

 

补充:
  Integer.MAX_VALUE:

public final class Integer extends Number implements Comparable<java.lang.Integer> {
*/
/**
* A constant holding the minimum value an {@code int} can
* have, -2<sup>31</sup>.
*//*

@Native
public static final int MIN_VALUE = 0x80000000;

*/
/**
* A constant holding the maximum value an {@code int} can
* have, 2<sup>31</sup>-1.
*//*

@Native public static final int MAX_VALUE = 0x7fffffff;

*/
/**
* The {@code Class} instance representing the primitive type
* {@code int}.
*
* @since JDK1.1


参考:
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

标签:minprice,int,maxprofit,public,121,差值,prices,数据结构,leetcode
From: https://www.cnblogs.com/yzhone/p/17046824.html

相关文章

  • [LeetCode] 2281. Sum of Total Strength of Wizards
    Astherulerofakingdom,youhaveanarmyofwizardsatyourcommand.Youaregivena 0-indexed integerarray strength,where strength[i] denotesthest......
  • [LeetCode] 1519. Number of Nodes in the Sub-Tree With the Same Label
    Youaregivenatree(i.e.aconnected,undirectedgraphthathasnocycles)consistingof n nodesnumberedfrom 0 to n-1 andexactly n-1 edges.Th......
  • LeetCode & Top Interview Questions All In One
    LeetCode&TopInterviewQuestionsAllInOnehttps://leetcode.com/problem-list/top-interview-questions/?difficulty=EASY&page=1&status=NOT_STARTED(......
  • LeetCode.203 移除链表元素
    1.题目:给你一个链表的头节点 ​​head​​ 和一个整数 ​​val​​ ,请你删除链表中所有满足 ​​Node.val==val​​ 的节点,并返回 新的头节点 。 示例:输入:head=......
  • LeetCode无重复字符的最长子串(unordered_set/kmp滑动窗口)
    原题解unordered_set题目给定一个字符串s,请你找出其中不含有重复字符的最长子串的长度。约束解法方法一classSolution{public:intlengthOfLonge......
  • 《数据结构 - C语言》单链表
    目录结构定义初始化建立清空求表长判断是否为空表取值查找插入删除销毁遍历打印测试结构定义#include<stdio.h>#include<malloc.h>#include<stdlib.h>#defineOK......
  • 【BFS】LeetCode 133. 克隆图
    题目链接133.克隆图思路代码classSolution{publicNodecloneGraph(Nodenode){if(node==null){returnnode;}H......
  • 什么是数据结构
    数据结构是一门研究非数值计算的程序设计问题中的操作对象,以及它们之间的关系和操作等相关问题的学科。什么是数据数据是描述客观事物的符号,是计算机中可以操作的对象,......
  • 【LeetCode链表#6】移除链表元素
    移除链表元素题目力扣题目链接(opensnewwindow)题意:删除链表中等于给定值val的所有节点。示例1:输入:head=[1,2,6,3,4,5,6],val=6输出:[1,2,3,4,5]示例2:输......
  • leetcode-easy-两数之和
    两数之和一解题思路:使用循环的方法从前到后计算给出的数组,直到找到目标题目#给定一个整数数组nums和一个整数目标值target,请你在该数组中找出和为目标值target......