详细见: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