LeetCode121 Best Time to Buy and Sell Stock

本文介绍了一个经典的算法问题:寻找数组中最大利润的买入和卖出时机。通过一次遍历实现高效求解,适用于股票交易等场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

详细见:leetcode.com/problems/best-time-to-buy-and-sell-stock


Java Solution: github

package leetcode;

/*
 * 	Say you have an array for which the ith element is the price of 
 * 	a given stock on day i.

	If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
	
	Example 1:
	Input: [7, 1, 5, 3, 6, 4]
	Output: 5
	
	max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
	Example 2:
	Input: [7, 6, 4, 3, 1]
	Output: 0
	
	In this case, no transaction is done, i.e. max profit = 0.
 */

public class P121_BestTimetoBuyandSellStock {
	public static void main(String[] args) {
		Solution s = new Solution();
		System.out.println(s.maxProfit(new int[] {1, 2, 3, 4, 5}));
		System.out.println(s.maxProfit(new int[] {5, 4, 3, 2, 1}));
		System.out.println(s.maxProfit(new int[] {7, 1, 5, 3, 6, 4}));
	}
	/*
	 * 	AC
	 * 	3 ms
	 */
	static class Solution {
	    public int maxProfit(int[] prices) {
	    	if (prices == null) {
	    		return 0;
	    	}
	    	int min = Integer.MAX_VALUE;
	    	int ans = 0;
	    	for (int i = 0; i < prices.length; i ++) {
	    		min = Math.min(min, prices[i]);
	    		ans = Math.max(ans, prices[i] - min);
	    	}
	        return ans;
	    }
	}
}


C Solution: github

/*
    url: leetcode.com/problems/best-time-to-buy-and-sell-stock
    onn: AC 573ms 11.84%
    on:  AC   6ms 29.39%
    on_1: AC  3ms 49.12%
*/

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

int onn(int* p, int pn) {
    int m = 0, i = 0, j = 0;
    for (i = 0; i < pn; i ++) {
        for (j = i+1; j < pn; j ++) {
            m = m < p[j]-p[i] ? p[j]-p[i] : m;
        }
    }
    return m;
}

int on(int* p, int pn) {
    int* m = NULL, i = 0, a = 0, mi = -1;
    if (pn == 0) return a;
    m = (int*) malloc(sizeof(int) * (pn+1));
    for (i = 0; i < pn; i ++) {        
        while (mi != -1 && m[mi] > p[i]) {
            mi --;
        }
        if (mi == -1) {
            m[++ mi] = p[i];
        } else {
            a = a < p[i] - m[mi] ? p[i] - m[mi] : a;
        }
    }
    free(m);
    return a;
}

int on_1(int* p, int pn) {
    int mv = INT_MAX, a = 0, i = 0, v = 0;
    for (i = 0; i < pn; i ++) {
        v = p[i];
        mv = mv < v ? mv : v;
        a = a > v - mv ? a : v - mv;
    }
    return a;
}

int maxProfit(int* p, int pn) {
    return on_1(p, pn);
}

int main() {
    int p[] = {4, 0, 1, 3, 5, 6, 2};
    int pn = 7;
    printf("answer is %d\n", maxProfit(p, pn));
}


Python Solution: github

#coding=utf-8

'''
    url: leetcode.com/problems/best-time-to-buy-and-sell-stock
    @author:     zxwtry
    @email:      zxwtry@qq.com
    @date:       2017年5月5日
    @details:    Solution:  68ms 26.43%
'''

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        ans, mv = 0, 1<31
        for i in prices:
            mv = min(mv, i)
            ans = max(ans, i-mv)
        return ans





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值